目前
- 我有一个父组件在将函数传递给子组件时作出 react
- 子组件给函数添加一个变量
- 该函数有一个可选的回调,当提供该函数运行时记录 2 条控制台消息(如预期):
hello world!
hello mars!
react 脚本:
class App extends Component {
parentFunction = (optional_callback, variable_defined_in_child) => {
console.log("hello " + variable_defined_in_child);
if (optional_callback) {optional_callback()};
}
myCallback = () => {
console.log("hello mars!");
}
render () {
<ChildComponent
myFunction = {this.parentFunction.bind(this, myCallback)}
/>
}
}
const ChildComponent = props => {
const newVariable = "world!";
props.myFunction(newVariable);
}
问题
如果未提供回调,则期望收到控制台消息:
hello world!
但是 variable_defined_in_child
被定位在 optional_callback
的位置并且函数失败。
问题
是否可以从子组件访问props.myFunction
的绑定(bind)变量,检查是否有回调,如果没有,提供为null
?
- 注意:我是 React 的新手,所以如果我使用反模式编码,请告诉我,但如果不是,我想了解我的请求是否可行,而不是重构代码。
最佳答案
您可以将 parentFunction
更改为返回另一个函数的函数。 (如果您是这个概念的新手,它可能看起来很复杂,但不要担心。)
想象 parentFunction
是:
parentFunction = optional_callback => variable_defined_in_child => {
console.log("hello " + variable_defined_in_child);
if (optional_callback) {
optional_callback();
}
};
然后以这种方式将其传递给 ChildComponent
:
<ChildComponent
myFunction={this.parentFunction.bind(this, this.myCallback)()}
/>
那么这里发生了什么?
您正在将 parentFunction
与 this
绑定(bind)并将 this.myCallback
作为参数传递给它,然后调用
这将返回一个接受单个参数 variable_defined_in_child
的函数,该参数完全符合您的要求:console.log
等等...同时可以访问 this .myCallback
而不将其作为参数传递。
如果您不将 this.myCallback
传递给 parentFunction
,一切仍然正常。
这是一个有效的 CodeSandbox
您的代码将是:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
parentFunction = optional_callback => variable_defined_in_child => {
console.log("hello " + variable_defined_in_child);
if (optional_callback) {
optional_callback();
}
};
myCallback = () => {
console.log("hello mars!");
};
render() {
return (
<ChildComponent
myFunction={this.parentFunction.bind(this, this.myCallback)()}
/>
);
}
}
const ChildComponent = props => {
const newVariable = "world!";
props.myFunction(newVariable);
return <div />;
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
关于javascript - 是否可以在 React 中检查和/或更改绑定(bind)变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56097982/