这可能听起来很傻,但我找不到这方面的指南。
我想要做的是更改update父级中命名的变量。
并在父 DOM 中执行以下操作:
<Child update={this.state.update} />
Run Code Online (Sandbox Code Playgroud)
在孩子中,而不是在渲染和返回(with const {update} = this.props)之间拾取它并且只能在 DOM 中使用它,我想在构造函数和渲染之间的部分拾取它并在那里的函数中使用它.
您可以props在组件中的任何位置访问组件,无论它是constructor, lifecycle functions, render or custom functions.
您唯一需要知道的是React 组件的上下文constructor, lifecycle methods and render function已经有了,但是您需要自己添加绑定。绑定可以在或 中通过将函数声明为 来完成。bindingcustom function constructor arrow functions
检查这个答案,了解为什么需要绑定自定义函数:Why do we need to bind function and eventHandlers in React and What is the Difference Between the different Binding Method
对于您的情况
<Child update={this.state.update} />
Run Code Online (Sandbox Code Playgroud)
孩子可能在哪里
class Child extends React.Component {
componentDidMount() {
const {update} = this.update || {};
console.log(update);
this.somefunc();
}
somefunc = () = {
const {update} = this.update || {}; //After function is binded, you can do the same thing here too
console.log(update);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2463 次 |
| 最近记录: |