首页 文章

包装输入时,React道具未正确设置

提问于
浏览
2

我正在尝试创建一个React组件,它包装一个输入并将更改的输入值传递给它的父项 . 我可以通过委托onchange函数trought props将事件传递给父级,但我更愿意封装从子组件中的事件中提取新值 .

这是我的组件代码:

class BigInputField extends React.Component<IBigInputField, {}>{
  handleChange(event){
    console.log("handleChange method called !");
    debugger;
    let value = event && event.target && event.target.value;
    this.props.onChangeSetValue(value);
  };
  render(){
    return (
        <input type="search" value = {this.props.value} onChange= {this.handleChange} id="main_search_field" className="form-control" placeholder="Stuff to input"/>
    );
  }
}

问题是,当我在输入中输入内容时,反应抱怨this.props.onChangeSetValue(value)不是函数 . 当我在调试器语句中检查this.props时,我得到一个值为“form-control”的className成员,一个值为“Stuff to input”的占位符,其值为“main_search_field”....似乎不是获取由父母传递的道具,我得到我的组件呈现的孩子的道具!这可能是chrome调试器的一个问题,它没有正确设置这个值,但它没有解释为什么我的this.props.onChangeSetValue似乎不存在 .

在父级中,prop设置如下:

<BigInputField onChangeSetValue= {this.setSearchValue} value= this.state.search}/>

我已经检查了父项的render函数,“this.setSearchValue”是正确的函数 .

你怎么解释这个?

谢谢 .

2 回答

  • 0

    你有 this 绑定到您的组件?在React组件中使用es6扩展时,你应该做这样的事情:

    class BigInputField extends React.Component<IBigInputField, {}>{
        constructor(props) {
            super(props);
            //need to bind custom functions to the component due to how extends works in es6
            this.handleChange = this.handleChange.bind(this);
        }
        ...
        render () { // return here }
    }
    
  • 2

    根据文档,当使用ES6类时,没有像React.createClass那样在渲染中传递的方法的自动绑定,我必须在render方法中将它们绑定在这样:

    render(){
        return (
            <input type="search" value = {this.props.value} onChange= {this.handleChange.bind(this)} id="main_search_field" className="form-control" placeholder="Stuff to input"/>
        );
      }
    

    注意 this.handlechange 之后的绑定

相关问题