React利用jsx语法,使得html和js语法可以混写。
最简单的使用
把写好的html模板,通过ReactDOM.render方法挂载到root元素上,第一个参数是模板(只能有一个根节点),第二个参数是要挂载到的节点。
<div id="root"></div>
const element = <h1>hello</h1>
React.render(
element,
document.getElementById("root")
)
样式设置
注意在react中的class不能直接使用,而是要用className。因为class是关键字。
const element = <h1 className="hello">hello</h1>
还可以直接写在组件上,相当于行内样式,style属性写在花括号中,花括号中也要是一个对象。
const element = <h1 style={{color: "red"}}>hello</h1>
或者:
var helloStyle = {
color: blue,
font-size: 20px
}
const element = <h1 style={helloStyle}>hello</h1>
状态和生命周期
这里先区分一下state和props的区别,首先props是用来接收父组件和外部传来的值,而状态是一个组件内部自带的属性。
利用constructor初始化this.state
var Hello React.createClass({
constructor(props){
super(props);
this.state = {sex: 'women'}
}
render(){
return (
<h1>I am a {this.state.sex}</h1>
)
}
})
修改state
如果只是简单的修改,直接给setState一个对象。
this.setState({sex: 'man'});
因为state可能是异步更新的,所以我们不能依赖props的值去计算下一个state。如下代码是不正确的:
this.setState({
count: this.state.count + this.props.increment
})
我门可以使用setState的第二种格式,让setState接收一个函数,该函数的第一个参数是当前的状态值,第二个参数是要更新的值。
this.setState(function(curState, props){
return {
conut: curState.count + props.increment
}
})
钩子函数
var Hello React.createClass({
constructor(){
this.state = {sex: 'women'}
},
componentWillMount(){
console.log("挂载之前:稍等我很快就要开始了");
}
componentDidMount(){
console.log("挂载完成:计时开始");
}
componentWillReceiveProps (){
console.log("当接收到一个新的props:我接收到一个props");
}
componentWillUnmount(){
console.log("组件将要被销毁:我要被销毁了!!");
}
componentWillUpdate(){
console.log("组件即将更新:1秒即将过去!");
}
componentDidUpdate(){
console.log("组件更新之后:一秒就这样过去了");
}
shouldComponentUpdate(){
console.log('组件渲染之前'); //具体请看性能优化
}
render(){
return (
<h1>I am a {this.state.sex}</h1>
)
}
})
事件相关
react的事件绑定一定要确定知道是谁要触发这个事件,把事件绑在真正触发的元素上。
比如上面子向父传值的例子,事件一定要绑在input元素上
,如果在父组件中绑在SearchBar
上是没有办法触发的。
绑定好事件之后,在触发的函数中通过e.currentTarget.value
获取表单选中/输入的值。
<input
onKeyPress={e => {
console.log(e.currentTarget.value);
}}
/>
e.currentTarget和e.target的区别
-
currentTarget:获取绑定该事件元素,一般需要应该都是用这个。
-
target:获取真正触发该事件的元素,如果点击事件就是得到真正点击到的那个元素。
获取组件自定义属性
如果想要获取组件的自定义属性,比如一个列表,想要点击某一条获取其对应的索引。我们需要在组件上添加data-xxx
属性。然后在方法中通过e.currentTarget.getAttribute('data-xxx')
方法获取。
deleteHandle = e=> {
console.log(e.currentTarget.getAttribute('data-index')); //获取到对应的索引
}
{this.state.customerList.map((item, index) => (
<div data-index={index} onClick={this.deleteHandle}></div>
)}
ref属性
react的ref
属性表示对组建真正实例的引用,也就是ReactDOM.render()
后渲染出的真正dom
节点。该属性值可以是一个字符串也可以是一个回调函数(推荐)。
先看一下属性值是一个回调函数的使用:
loadMore() {
console.log(this.bodyBox.clientHeight) //打印该元素可视区域的高度
}
<div
ref={c => {
this.bodyBox = c; //将dom节点赋值给this.bodyBox
}}
onScroll={this.loadMore}
>
或者(与上面效果一样):
loadMore(c) {
console.log(c.clientHeight)
}
<div
ref={this.loadMore}
>
如果属性值是一个字符串的话:
<input ref="input" />
let inputEl = this.refs.input; //在其他位置访问该组件实例的dom节点
网友评论