【问题标题】:React component: Simulate standard HTML <input/> APIReact 组件:模拟标准 HTML <input/> API
【发布时间】:2019-06-25 17:47:07
【问题描述】:

我想像任何标准输入元素一样使用 API 制作一个组件,这意味着我想像这样使用它:&lt;CustomInput value={this.state.custom_input_state} onChange={this.handleChange} /&gt;

这是我目前所拥有的,但我不知道如何

  • 使自定义组件值可从父组件更改 建成后
  • 使父级的 onChange 处理函数在 自定义组件的值变化

这是我的测试设置:

class Form extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            foo: 0
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.increment = this.increment.bind(this);
    }

    handleChange(event) {
        this.setState({[event.target.name]: event.target.value});
    }

    handleSubmit(event) {
        alert(this.state.foo);
        event.preventDefault();
    }

    increment() {
        this.setState({foo: this.state.foo + 1});    
    }

    render() {
        return(
            <form onSubmit={this.handleSubmit}>
                <div onClick={this.increment}>Increment from parent</div>
                <CustomInput name="foo" value={this.state.foo} onChange={this.handleChange}/>
                <input type="submit" value="Submit" />
            </form>
        )
    }
}


class CustomInput extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            value: this.props.value,
        };
        this.increment = this.increment.bind(this);
    }

    increment() {
        this.setState({value: this.state.value + 1});    
    }

    render() {
        return(
            <React.Fragment>
                <div onClick={this.increment}>Increment self</div>
                <input name={this.props.name} value={this.state.value}/>
            </React.Fragment>
        );
    }
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您必须将所有 CustomInput 道具传递给输入元素。在 CustomInput 组件中实际上它没有收到 onChange 事件。

    将 prop onChange 事件传递给输入元素

    表单组件

    class Form extends Component {
      constructor() {
        super();
        this.state = {
          foo: 'React'
        };
      }
    
      handleChange = (event) => {
        this.setState({
          [event.target.name]:event.target.value
        })
      }
    
      render() {
        return (
          <div>
            <form>
              <Custominput name="foo" onChange={this.handleChange} value={this.state.foo} />
            </form>
            {this.state.foo}
          </div>
        );
      }
    }
    

    自定义输入组件

    export default class CustomInput extends React.Component{
    
    
      render(){
        return(
            <input {...this.props} />
        )
      }
    }
    

    演示link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 2016-03-06
      • 2011-09-30
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      相关资源
      最近更新 更多