[英]How to access state within a property of a React class component?
I've got a React Class Component of which I would like to separate a part of the rendered JSX but I don't seem to be able to get the Component's state within the separated JSX (as a property of the class).我有一个 React Class 组件,我想从中分离出渲染的 JSX 的一部分,但我似乎无法在分离的 JSX 中获得组件的 state(作为类的属性)。
The actual situation is very similar to this example实际情况和这个例子很相似
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
x: 1
};
}
button = (
<button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
);
render() {
return (
<>
x = {this.state.x}
<button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button> // this works!
{this.button} // this doesn't :(
</>
);
}
}
Now, when I try to read this.state.x
directly in the render() method, it works as expected, but when I put the code in the button
property and inject it in the render() method by calling this.button
inside brackets then this.state
is undefined and I'm unable to read the state.现在,当我尝试直接在 render() 方法中读取this.state.x
时,它按预期工作,但是当我将代码放在button
属性中并通过调用this.button
将其注入到 render() 方法中时括号然后this.state
未定义,我无法读取 state。
I tried using an utility method like getX = () => this.state.x
and called it inside the button
property but it doesn't get the state.我尝试使用像getX = () => this.state.x
这样的实用方法,并在button
属性中调用它,但它没有得到 state。
I also tried setting another property _this = this
and calling this._this.getX
inside the brackets.我还尝试设置另一个属性_this = this
并在括号内调用this._this.getX
。 This didn't work either.这也没有用。
Any idea on how to get it to work?关于如何让它工作的任何想法? Any help is appreciated!任何帮助表示赞赏!
Using arrow function you will get the implicit reference of the component instance:使用箭头 function 您将获得组件实例的隐式引用:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
x: 1
};
}
renderButton = () => (
<button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
);
render() {
return (
<>
x = {this.state.x}
<button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
{this.renderButton()}
</>
);
}
}
Using function syntax, you need to bind this
in constructor:使用 function 语法,您需要在构造函数中绑定this
:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
x: 1
};
renderButton = renderButton.bind(this);
}
renderButton() {
return <button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
};
render() {
return (
<>
x = {this.state.x}
<button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
{this.renderButton()}
</>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.