【问题标题】:Function passed to child is being interpreted as a string传递给子函数的函数被解释为字符串
【发布时间】:2019-06-24 18:29:43
【问题描述】:

在 React 中,我试图从从子组件传输到其父组件的单选按钮中获取值。为此,我在父级中创建了一个函数并将其作为道具传递给子级:

handleOptionChange = e => {
  this.setState({
    selectedOption: e.target.value
  });
};

<RadioRental handleOptionChange="this.handleOptionChange" />;

这就是我在孩子身上所拥有的:

class RadioRental extends Component {
  render() {
    return (
      <div className="form-check">
        <label>
          <input
            type="radio"
            name="react-tips"
            value="saloon"
            checked={this.props.selectedOption === "option_saloon"}
            onChange={this.props.handleOptionChange}
            className="form-check-input"
          />
          Saloon car
        </label>
      </div>
    );
  }
}

这会产生以下编译错误:

index.js: 1446 警告:预期onChange 侦听器是一个函数,而不是string 类型的值。

有什么建议吗?

【问题讨论】:

  • 欢迎来到 Stack Overflow。如果您发现针对该问题发布的任何答案有帮助,请单击答案旁边的勾选按钮以接受该答案作为该问题的答案。请查看tourHow to Ask 页面。看来您过去没有接受任何答案。如果您不开始接受答案,您可能会在某些情况下收到question ban

标签: reactjs function components react-props


【解决方案1】:

你必须在你的父母中使用{} 符号:

<RadioRental handleOptionChange={this.handleOptionChange} />;
//------------------------------^-----------------------^

{} 表示法将事物视为 JavaScript 与 "" 是字符串属性。

最终代码

handleOptionChange = e => {
  this.setState({
    selectedOption: e.target.value
  });
};

<RadioRental handleOptionChange={this.handleOptionChange} />;

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 1970-01-01
    • 2016-12-08
    • 2011-05-12
    • 2016-01-28
    • 2013-12-11
    相关资源
    最近更新 更多