在ReactJS中更改构造函数属性

问题描述 投票:0回答:2

我有一个关于反应构造函数的问题,因为我使用了角度和习惯于方式绑定行为。我不知道如何从构造函数更改属性。并解释我如何做不到这一点,并解释我如何实现我的目标。

class example extends React.Component {
 constructor(){
   super();
   this.changeExample = this.changeExample.bind(this)
   this.valueExample = 'Hello Example'
 }
 changeExample() {
   this.valueExample = 'Hello StackOverFlow'
 }
 render()
 return(
   <button onClick="{this.chnageExample}"></button>
   <div className="example">{this.valueExample}</div>
 )

}
reactjs constructor properties
2个回答
1
投票

在您的示例中,您应该在状态中使用值Example。在构造函数中,您为组件设置初始状态

constructor(props){
    super(props)
    this.state = { valueExample: "" }
}

changeExample(){
   this.setState({ valueExample: "Hello ..." })
}

单击按钮后,组件将重新渲染,valueExample将在视图中更新。

在react中,组件(视图)仅在组件的状态或道具发生更改时才更新(重新渲染)。你可以阅读reactjs https://reactjs.org/docs/components-and-props.html https://reactjs.org/docs/state-and-lifecycle.html的文档


0
投票

他有权利。首先必须使用this.state,因为我们必须设置初始状态,然后使用this.setState获取新值(没有仪表专业或我们希望的女巫状态)

© www.soinside.com 2019 - 2024. All rights reserved.