一.前提认识 在 HTML 中,表单元素如 input, textarea 和 select 表单元素通常保持自己的状态,并根据用户输入进行更新。而在 React 中,可变状态一般保存在组件的 state(状态) 属性中,并且只能通过 setState() 更新。二.受控组件 1.网址:http://www.css88.com/react/docs/forms.html 2.定义:我们可以通过使 React 的 state 成为 “单一数据源原则” 来结合这两个形式。然后渲染表单的 React 组件也可以控制在用户输入之后的行为。这种形式,其值由 React 控制的输入表单元素称为“受控组件”。。 组件自己本身并不更新值,而是把值传递给父组件,让父组件决定是否更改。一般通过给子组件设置value属性,再配置一个onchange处理。 3.代码: 3.1.父组件 class Parent extends Component { constructor(props) { super(props); this.state = {value: 1}; this.onChangeHandle = this.onChange.bind(this); } onChange(event) { //处理值 if (改) { this.setState({value: event.target.value}); } } render() { return NumberInput value={this.state.value} onChange={this.onChangeHandle} ; } } 3.2.子组件NumberInput class NumberInput extends Component { constructor(props) { super(props); this.state = { value: props.value }; this.onChangeHandle = this.onChange.bind(this); } //接收到新的属性时更新state componentWillReceiveProps(nextProps) { this.setState({ value: nextProps.value }); } onChange(event) { //通知父组件值更新了 this.props.onChange(event); } render() { return className="NumberInput" input type="text" value={this.state.value} onChange={this.onChangeHandle} } }三.非受控组件 1.网址:http://www.css88.com/react/docs/uncontrolled-components.html 2.定义:在大多数情况下,我们推荐使用受控组件来实现表单。在受控组件中,表单数据由 React 组件负责处理。另外一个选择是不受控组件,其表单数据由 DOM 元素本身处理。 组件自己控制组件的状态,一般父组件会给它也一个初始值(通过defaultValue属性)。 3.1.父组件 class Parent extends Component { render() { return NumberInput defaultValue=20 ; } } 3.2.子组件NumberInput class NumberInput extends Component { render() { return className="NumberInput" input type="text" defaultValue={this.props.defaultValue} } }四.结合使用受控组件与非受控组件 1.使用场景:当写一个基础组件的时候 2.代码: 2.1.父组件 与上面类似 把子组件当受控组件: render() { return NumberInput value={this.state.value} onChange={this.onChangeHandle} ; } 把子组件当非受控组件: render() { return NumberInput defaultValue={this.state.value} ; } 2.2.子组件NumberInput class NumberInput extends Component { constructor(props) { super(props); this.state = { value: props.value }; this.onChangeHandle = this.onChange.bind(this); } //接收到新的属性时更新state componentWillReceiveProps(nextProps) { this.setState({ value: nextProps.value }); } onChange(event) { //通知父组件值更新了 this.props.onChange(event); } render() { let val = {}; //判断组件的props属性是否有value属性,有的话,是受控组件,没有的话是非受控组件 判断组件的props属性是否有value属性 ? (val = {'defaultValue': this.props.defaultValue}) : (val = {'value': this.state.value}); return className="NumberInput" input type="text" {...val} onChange={this.onChangeHandle} ; } }
react受控组件与 v非受控组件
最新推荐文章于 2023-05-07 09:21:38 发布