初始的效果圖:bash
class Element extends React.Component{
handleClick(){
// 經過js id 獲取DOM
const ipt = document.querySelector('input');
ipt.style.background = 'hotpink';
}
render() {
return (
<div>
<input
type = "button"
defaultValue = "操做DOM"
onClick = {this.handleClick}
/>
</div>
)
}
};
ReactDOM.render(
<Element />,
document.querySelector('#app')
);
複製代碼
點擊後效果圖: app
class Element extends React.Component{
handleClick(e){
// 2. 事件對象
const {target} = e;
console.log(target);
target.style.background = 'skyblue';
}
render() {
return (
<div>
<input
type = "button"
defaultValue = "操做DOM"
onClick = {this.handleClick}
/>
</div>
)
}
};
ReactDOM.render(
<Element />,
document.querySelector('#app')
);
複製代碼
點擊後效果圖: dom
class Element extends React.Component{
handleClick(){
// 3. 經過 ref 屬性操做Dom
console.log( this );
console.log( this.refs );
console.log( this.refs.ipt );
this.refs.ipt.style.background = 'yellow';
}
render() {
return (
<div>
<input
ref = {"ipt"}
type = "button"
defaultValue = "操做DOM"
onClick = {this.handleClick.bind(this)}
/>
</div>
)
}
};
ReactDOM.render(
<Element />,
document.querySelector('#app')
);
複製代碼
ref屬性的值最好寫成回調函數的形式: ref={itemDiv=>this._div=itemDiv}函數
點擊後效果圖:ui
class Element extends React.Component{
handleClick(){
// 4. findDOMNode
const ipt = document.querySelector('input');
ReactDOM.findDOMNode(ipt).style.background = 'purple';
}
render() {
return (
<div>
<input
ref = {"ipt"}
type = "button"
defaultValue = "操做DOM"
onClick = {this.handleClick}
/>
</div>
)
}
};
ReactDOM.render(
<Element />,
document.querySelector('#app')
);
複製代碼
點擊後效果圖:this
注:在使用 ReactDOM.findDOMNode時,當參數是DOM時,返回值是此DOM;
當參數是Component時,獲取的就是Component的render中dom。spa
組件兩個重要概念: state,props
state(狀態):負責用戶界面
props(屬性):組件傳值通信3d
democode
//List子組件
class List extends React.Component{
render() {
console.log( this.props );
return (
<div>
<h2>{this.props.abc}</h2>
<h2>{this.props.data}</h2>
{
// 子組件去調用父組件的方法
// 子組件向父組件通信
}
<button onClick={this.props.fn.bind(this,'傳參')}>事件按鈕1</button>
<button onClick={()=>{this.props.fn('傳參123')}}>事件按鈕2</button>
</div>
);
}
};
//Element父組件
class Element extends React.Component{
state = {
data: '父組件的數據'
}
getData(xyz){
console.log('getData函數',xyz)
}
render() {
return (
<div>
<h1> 組件 </h1>
<List
abc={'list'}
data={this.state.data}
fn={this.getData}
></List>
</div>
)
}
};
ReactDOM.render(
<Element />,
document.querySelector('#app')
);
複製代碼
效果圖: cdn