【问题标题】:React props not correctly set when wrapping an input包装输入时未正确设置 React 道具
【发布时间】:2015-12-17 08:47:12
【问题描述】:

我正在尝试创建一个 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”的 id ...。 似乎我没有得到父级传输的道具,而是得到了我的组件渲染的子级道具! 这可能是 chrome 调试器的问题,它没有正确设置 this 值,但它没有解释为什么我的 this.props.onChangeSetValue 似乎不存在。

在父级中,prop 是这样设置的:

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

我已经在父级的渲染函数中检查了“this.setSearchValue”是正确的函数。

你怎么解释这个?

谢谢。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    根据文档,在使用 ES6 类时,不会像 React.createClass 那样自动绑定在 render 中传递的方法,我必须在 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之后的绑定

    【讨论】:

      【解决方案2】:

      您是否将this 绑定到您的组件?在 React 组件中使用 es6 extends 时,你应该这样做:

      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 }
      }
      

      【讨论】:

      • 另一个相关问题:组件是否有一个构造函数,该构造函数接受 props 并调用 super(props),就像在 tell' sn-p 中一样?
      • 谢谢,我在 React 文档中读过,但忘记了。 无自动绑定方法遵循与常规 ES6 类相同的语义,这意味着它们不会自动将 this 绑定到实例。您必须明确使用 .bind(this) 或箭头函数 =>。 但我更喜欢这种方式:render(){ return ( &lt;input type="search" value = {this.props.value} onChange= {this.handleChange.bind(this)} id="main_search_field" className="form-control" placeholder="Stuff to input"/&gt; ); } 这不会强迫我实现构造函数(至少我猜是这样)。跨度>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 2022-11-27
      • 2020-08-14
      • 2018-08-11
      相关资源
      最近更新 更多