为什么我的 onChange/onBlur 处理程序无法在自定义组件 (reactjs) 上工作

why I can't get my onChange/onBlur handler work on custom component (reactjs)

为什么我的 onChange 处理程序无法在子自定义组件上运行?我错过了什么。你们能帮我解决方案吗,如果有最佳实践可以告诉我。 谢谢。

示例代码:

var TextBox = React.createClass ({
 getDefaultProps: function() {
     return {
         className: 'input-box'
     };
 },

 render() {
     return (
        <input type="text" />
    );
 }
});

var Dashboard = React.createClass({
 handleChange() {
  alert('test');
 }

 render() {

     return (
         <div>
             <h1>Components</h1>
             <label>Input Box</label><br/>
             <TextBox onBlur={this.handleChange} type="text" placeholder="hints (optional)"/>
         </div>
     )
 }
});
//ReactDOM.render goes here...

您需要使用回调来获取父组件的变化

尝试如下,

class TextBox extends React.Component {
  render() {
    return (
      <input onBlur={this.props.callBack} type="text" />
    );
  }
}
class Dashboard extends React.Component {
  render() {
    const handleChange = () => {
      console.log('---');
    }
    return (
      <div>
        <h1>Components</h1>
        <label>Input Box</label><br/>
        <TextBox callBack={handleChange} type="text" placeholder="hints (optional)"/>
      </div>
    );
  }
}

React.render(
  <Dashboard />,
  document.getElementById('react_example')
);

您需要将事件处理程序作为道具一直传递到输入组件。实际上,您的 input 没有设置事件绑定。

确保所有道具都传递到最里面的 child 的一种简单方法是使用 the spread operatorTextBox 组件中的所有道具传递到child.

因此,您的 TextBox 组件渲染函数将如下所示:

 render() {
   return (
     <input { ...this.props } type="text" />
   );
 }

就是这样!您传递给 <TextBox /> 的所有道具都会进入 <input>