react --style绑定
style字面量对象绑定
// state数据
this.state = {
a:10,
b:20,
txtColor:"#ff0000"
}
//属性绑定
<p style={{color:this.state.txtColor,fontWeight:"bold"}}>react中的style属性可以绑定一个对象。</p>
style方法绑定
//方法绑定
<p style={this.txtStyleObj()}>style属性可以绑定一个对象字面量,也可以绑定一个方法调用,方法中返回style对象。</p>
txtStyleObj = e=>{
return {
border:"solid 1px "+this.state.txtColor,
fontSize:"30px"
}
}
react-- class绑定
{/* react中的className如果需要绑定数组,需要调用数组的join方法,然后绑定 */}
<p className={["MyCom-bgcolor","MyCom-border"].join(" ")}>react中的className属性不能直接绑定数组和对象</p>
<p className={true?"MyCom-bgcolor ":""}>对于需要通过一个布尔值来控制是否拥有某个class,可以通过三目运算符</p>
页面渲染
demo
import React, { Component } from 'react';
import "./MyCom.css";
class MyCom extends Component {
constructor(props) {
super(props);
this.state = {
a:10,
b:20,
txtColor:"#ff0000"
}
}
render() {
return (
<div>
<p>{this.state.a}+{this.state.b}={this.sum()}</p>
<input type="color" value={this.state.txtColor} onChange={this.txtColorChange}></input>
<p style={{color:this.state.txtColor,fontWeight:"bold"}}>react中的style属性可以绑定一个对象。</p>
{/* react中style和class绑定之后,就不能再设置其他值。 */}
<p style={this.txtStyleObj()}>style属性可以绑定一个对象字面量,也可以绑定一个方法调用,方法中返回style对象。</p>
<hr/>
{/* react中的className如果需要绑定数组,需要调用数组的join方法,然后绑定 */}
<p className={["MyCom-bgcolor","MyCom-border"].join(" ")}>react中的className属性不能直接绑定数组和对象</p>
<p className={true?"MyCom-bgcolor ":""}>对于需要通过一个布尔值来控制是否拥有某个class,可以通过三目运算符</p>
</div>
);
}
// react中没有类似vue的计算结果,对于复杂的计算,需要写成一个计算方法,方法中返回计算的值,然后在模板中绑定这个方法调用。
sum=()=>{
return this.state.a+this.state.b;
}
txtColorChange=e=>{
this.setState({txtColor:e.target.value});
}
txtStyleObj = e=>{
return {
border:"solid 1px "+this.state.txtColor,
fontSize:"30px"
}
}
}
export default MyCom;