1. 操作DOM节点的方式
初始的效果图:
1.通过js的ID值获取DOM
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')
);
复制代码
点击后效果图:
2.通过事件对象e获取DOM
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')
);
复制代码
点击后效果图:
3. 通过 ref 属性操作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}
点击后效果图:
4. 通过 ReactDOM.findDOMNode 属性操作DOM
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')
);
复制代码
点击后效果图:
注:在使用 ReactDOM.findDOMNode时,当参数是DOM时,返回值是此DOM;
当参数是Component时,获取的就是Component的render中dom。
2.组件传参
组件两个重要概念: state,props
state(状态):负责用户界面
props(属性):组件传值通讯
demo
//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')
);
复制代码
效果图: