1、定義組件--組件===class##
class 名字 extends React.Component{
render(){
return <span>111</span>
}
};
2、使用組件##
ReactDOM.render(){
<名字 />,
document.getElementById('div1')
};
3、狀態(tài)##
屬性是固定的{this.props.name},狀態(tài)是可變的{this.state}
*向文本框中輸入數(shù)據(jù)span標(biāo)簽內(nèi)容也改變*
*初始化*
constructor(...args){
super(...args);//執(zhí)行父類的構(gòu)造函數(shù)
this.state={value:''};//子類的構(gòu)造函數(shù)
}
*方法*
fn(ev){
this.setState({
value:ev.target.value
});
}
*渲染*
render(){
return <div>
<input type="text" onChange={this.fn.bind(this)}>
<span>{this.state.value}</span>
</div>
}
4、react組件的生存周期#
componentWillMount()//創(chuàng)建之前
componentDidMount()//創(chuàng)建之后
componentWillUpdate()//更新之前
componentDidUpdate()//更新之后
componentWillUnmount()//卸載之前
componentWillReceiveRrops()//組件參數(shù)更新
5、父組件子組件###
*實(shí)現(xiàn)點(diǎn)擊按鈕數(shù)字依次加1*
class ChildComp extends React.Component{
render(){
return <span>{this.props.name}</span>;
}
}
class ParentComp extends React.Component{//父組件中渲染子組件
constructor(...args){
super(...args);
this.state={i:0};
}
fn(){
this.setState({
i:this.state.i+1
})
}
render(){
return <div>
<input type="button" value="點(diǎn)擊" onClick={this.fn.bind(this)}/>
<ChildComp name={this.state.i}/>
</div>;
}
}
window.onload=function(){
ReactDOM.render({
<ParentComp/>,
document.getElementById('example')
})
}
6、組件的節(jié)點(diǎn)refs##
class Title extends React.Component{
constructor(...args){
super(...args);
this.state={color:'black'};
}
fn(){
$(this.refs['s1'].css('color','red'))
}
render(){
return <div>
<input type="button" value="按鈕">
<span ref="s1">123456</span>
</div>
}
}
6、表單控件##
defaultValue={this.props.a}//定義初始化表單的內(nèi)容不用value
defaultChecked='true'//初始化單選框的狀態(tài)可改變
class Use extends React.Component{
render(){
return <form action="http://baidu.com" method="get">
<input type="text" defaultValue={this.props.a}/>
<input type="checkbox" defaultValue='true'/>
</form>
}
}
$(function(){
<Use a='blue'/>,
$('view')[0]
})
7、組件間的通信##
*父組件給子組件通信*
class Child extends React.Component{
constructor(...args){
super(...args);
}
render(){
return <div>{this.props.data_a}</div>
}
}
class Parent extends React.Component{
constructor(...args){
super(...args);
this.a=12;
}
render(){
return <div>
<Child data_a={this.a}/>
</div>
}
}
$(function(){
ReactDOM.render(
<Parent/>,
$('div')[0]
)
})
*子組件給父組件通信*
class Child extends React.Component{
constructor(...args){
super(...args);
this.num=12;
}
render(){
this.props.back(this.num);//獲取子組件參數(shù)
return <div>{this.props.data_a}</div>
}
}
class Parent extends React.Component{
constructor(...args){
super(...args);
this.a=12;
}
fn(num){//將子組件參數(shù)傳入父組件
alert(num)
}
render(){
return <div>
<Child back={this.fn.bind(this)}/>
</div>
}
}
$(function(){
ReactDOM.render(
<Parent/>,
$('div')[0]
)
})