Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

表单元素在react中的正确使用方式 #4

Open
Jenna-u opened this issue May 15, 2018 · 0 comments
Open

表单元素在react中的正确使用方式 #4

Jenna-u opened this issue May 15, 2018 · 0 comments

Comments

@Jenna-u
Copy link
Owner

Jenna-u commented May 15, 2018

在react中使用表单元素要注意以下几种情况:

1.input 相同的name会作为一组操作,例如checkbox; 在react中多次调用, 如果不区分name 和 id 默认只会生效第一个checkbox; name在input中一般是form提交时才使用

<div>
  <label htmlFor="apple">
     <input  id="apple" type="checkbox" name="demo"  /> apple
  </label>
  <label htmlFor="orange">
     <input  id="orange" type="checkbox" name="demo"  /> orange
  </label>
</div>

2.defaultChecked, defaultValue 是react的属性,在HTML中input只对 checked 和 value 生效。defaultChecked不能渲染后端传入的数据,且后端数据可能会变。两种方式可以解决:

// 第一种方式,用checked去渲染后端传入数据
<input 
  type="checkbox"
  checked={this.props.checked}
  defaultChecked=false
/>

// 第二种方式,把后端数据转嫁到span元素上,通过onChange去改变span的className来渲染选中样式,并且把checkbox置为visibility:hidden;
class CheckList extends Component {

  state = {
    isCheck: false
  }
 
  onCheck = e => {
     this.setState({
       isCheck: e.target.checked
     })
  }

  render() {
    return (
     <label>
       <input 
          type="checkbox"
          onChange={e => this.onCheck(e)}
       />
     <span className={this.state.isCheck ? 'checkedCls' :'checkCls'} />
    </label>
   )
 }
}

总结:

react推荐使用你的表单元素是controlled,所以尽量保持它是可控,推荐使用第一种,且改变表单元素的值状态用setState去操作。

参考:
react可控组件:https://reactjs.org/docs/forms.html#controlled-components

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant