我试图访问在componentDidMount方法中创建的变量。什么是最好的方法呢?
componentDidMount() {
var x = "hello";
}
bye() {
x = "bye";
}
render(){
return (<div onClick={this.bye}>)
}
答案 0 :(得分:1)
使用 this
(或state
,请参阅Fabian的回答。取决于您希望实现的目标)
componentDidMount() {
this.x = "hello";
}
bye() {
this.x = "bye";
}
render() {
return (<div onClick={this.bye}>)
}
答案 1 :(得分:1)
class Example extends React.Component {
constructor() {
super();
this.state = { x: "" };
this.bye = this.bye.bind(this);
}
componentDidMount() {
this.setState({ x: "hello" });
}
bye() {
this.setState({ x: "bye" });
}
render(){
return (<div onClick={this.bye}>{this.state.x}</div>)
}
}
ReactDOM.render(<Example/>, document.getElementById('View'));
<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="View"></div>