Javascript 如何更改React中组件的状态?
我是新的反应,并开始工作,以改变组件的状态。请问如何使用适当的对象来操纵这些值 Header.js组件Javascript 如何更改React中组件的状态?,javascript,reactjs,Javascript,Reactjs,我是新的反应,并开始工作,以改变组件的状态。请问如何使用适当的对象来操纵这些值 Header.js组件 //component with state and constructor import React, { Component } from 'react'; export class Header extends Component{ constructor(props){ super(props); this.state = {colors: this
//component with state and constructor
import React, { Component } from 'react';
export class Header extends Component{
constructor(props){
super(props);
this.state = {colors: this.props.color};
}
changeHeaderColor(){
//console.log('Change_header_color_was_clicked');
this.setState({
colors: this.props.colors = 'yellow'});
})
render(){
return(
<h1 style={{color:this.state.colors}}>This is the header Component <button onClick={this.changeHeaderColor}>Change Header Color</button></h1>
);
}
}
...
return (
<div className="App">
<Header color={'blue'}/>
<Header color={'red'}/>
...
//具有状态和构造函数的组件
从“React”导入React,{Component};
导出类头扩展组件{
建造师(道具){
超级(道具);
this.state={colors:this.props.color};
}
changeHeaderColor(){
//log('Change_header_color_was_clicked');
这是我的国家({
颜色:this.props.colors='yellow'});
})
render(){
报税表(
这是标题组件更改标题颜色
);
}
}
应用程序组件网
//component with state and constructor
import React, { Component } from 'react';
export class Header extends Component{
constructor(props){
super(props);
this.state = {colors: this.props.color};
}
changeHeaderColor(){
//console.log('Change_header_color_was_clicked');
this.setState({
colors: this.props.colors = 'yellow'});
})
render(){
return(
<h1 style={{color:this.state.colors}}>This is the header Component <button onClick={this.changeHeaderColor}>Change Header Color</button></h1>
);
}
}
...
return (
<div className="App">
<Header color={'blue'}/>
<Header color={'red'}/>
...
...
返回(
...
只需将这个.setState({colors:'yellow'});
在构造函数中,您必须像这样绑定changeHeaderColor
方法:
this.changeHeaderColor=this.changeHeaderColor.bind(this)
在构造函数中绑定函数,如:
this.changeHeaderColor = this.changeHeaderColor.bind(this);
或者改变这一点:
changeHeaderColor(){
this.setState({colors: this.props.colors = 'yellow'});
})
对于没有自己的此的箭头功能:
changeHeaderColor = () => {
this.setState({colors: this.props.colors = 'yellow'});
})
谢谢您的回复。但是它给我的输入错误!我附上了图片。