ReactDOM 将带参数的函数传递给子组件

ReactDOM passing a function with parameters to a child component

我是第一次在 React 中编程,我有一个问题,我不明白如何在不改变一切的情况下解决,但感觉必须有一个解决方案。

我在 index.js

处有此代码
export var updateString = function (test3){
    var test1 = 'hello world1'
    //do something mother
}

ReactDOM.render(<Child triggerUpdateString={() => updateString ('hello world3')}/>, document.getElementById('child'));

然后我在 child.js

得到了下面的代码
export default class Child extends React.Component {
  handleString = event => {
    event.preventDefault()
    this.props.triggerUpdateString('hello world2')
    //do something child }}

我在 "do something mother" 部分获取 'hello world1' 或 'hello world3' 没有问题,但我无法获取 'hello world2' 字符串。

如何从子项获取字符串到 updateString 函数?

您总是使用 "hello world3" 调用 updateString。这就是你没有看到它的原因。让你的回调 triggerUpdateString 基于参数。像这样:

ReactDOM.render(<Child triggerUpdateString={(str) => updateString (str)}/>, 
 document.getElementById('child'));

然后它应该适用于您作为参数传入的任何内容。 谢谢 欢迎反馈。

此处您将局部变量 test1 设置为常量值,但您传递的参数 (test3) 从未在任何地方使用:

export var updateString = function (test3){
    var test1 = 'hello world1'
    //do something mother
}

我认为你是想这样做,但在没有看到你的代码的情况下,我假设你在现实中的某个地方使用了这两个值:

export var updateString = function (test3){
    var test1 = test3;
    //do something mother
}

由于我们只是在这里进行测试,所以让我们将其更改为使用 console.log,以便我们在示例代码中得到有意义的结果:

export var updateString = function (test3){
    console.log(test3);
    //do something mother
}

现在,由于我们更改了 updateString 函数,我们不需要将其包装在额外的函数调用中来传递它:

<Child triggerUpdateString={() => updateString ('hello world3')}/>

你可以这样做:

<Child triggerUpdateString={updateString}/>

因为我们只是调用它并传递一个值:

this.props.triggerUpdateString('hello world2')

希望这个工作示例对您有所帮助,如果我有任何误解,请告诉我:

const updateString = function (newValue){
    console.log("new value:", newValue);
}

class Child extends React.Component {
  handleString = event => {
    event.preventDefault()
    this.props.triggerUpdateString('hello world2');
  }
  render() {
      return (<button onClick={this.handleString}>Test</button>)
  }
}

ReactDOM.render(<Child triggerUpdateString={updateString} />, document.getElementById('child'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="child"></div>