点击"变红"键,"aaa"颜色由黑变红。
未引入ref(将标签的style与组件的state绑定)
import React, { Component } from 'react';
class Red extends React.Component{
constructor(...args){
super(...args)
this.state={color:"black"}
}
fn(){
this.setState({
color:"red"
})
}
render(){
return <div>
<input type="button" onClick={this.fn.bind(this)} value="变红"/>
<span style={{color:this.state.color}}>aaa</span>
</div>
}
}
export default Red;
引入ref(通过ref直接操纵标签)
import React, { Component } from 'react';
class Red extends React.Component{
constructor(...args){
super(...args)
}
fn(event){
this.contentRef.style.color='red';
}
render(){
return <div>
<input type="button" onClick={this.fn.bind(this)} value="变红"/>
<span ref="{(content)=>{this.contentRef=content;}}">aaa</span>
</div>
}
}
export default Red;