React Forms笔记

  • onClick

事件参数可以获取控件引用,近而获取控件的props属性

onButtonClick = (evt) => {
    const btn = evt.target;
    console.log(`The user clicked ${btn.name}: ${btn.value}`);
};
render() { 
  return (
    <div>
        <h1>What do you think of React?</h1>
        <button name='button-1' value='great' onClick={this.onButtonClick}>
            Great
        </button>
        <button name='button-2' value='amazing' onClick={this.onButtonClick}>
            Amazing
        </button>
    </div>
); }
  • 表单组件引用

通过事件的target我们固然可以获得控件的引用,但是对于在表单内的控件来说,我们也可以通过ref属性来处理:his.refs.name.value获取input中定义的ref='name'

PS: evt.preventDefault();是为了阻止默认的表单行为

onFormSubmit = (evt) => { 
  evt.preventDefault(); 
  console.log(this.refs.name.value);
};
render() { 
  return (
      <div>
        <h1>Sign Up Sheet</h1>
        <form onSubmit={this.onFormSubmit}> 
          <input
            placeholder='Name'
            ref='name'
          />
          <input type='submit' />
        </form>
      </div> 
  );
}
powered by Gitbook最近更新 2018-09-04

results matching ""

    No results matching ""