标签:== cto author reac ons use info .text col
使用jsx的使用,用一个{}包裹起来,例如
const method = {<div> 123 </div>}
使用()小括号,防止分号自动插入
const element = ( <h1> Hello, {formatName(user)}! </h1> );
如果使用箭头函数,返回的是一个对象的话,使用()包围起来
const element = ( <h1> Hello, {formatName(user)}! </h1> );
通过props
function Comment(props) { return ( <div className="Comment"> <div className="UserInfo"> <Avatar user={props.author} /> <div className="UserInfo-name"> {props.author.name} </div> </div> <div className="Comment-text"> {props.text} </div> <div className="Comment-date"> {formatDate(props.date)} </div> </div> ); }
这样的话,就可以通过prop获得到数据,这个数据是只读的,不要修改
子组件向父组件传递数据
父: bindValue = (e) => { console.log(e)} <Son onChange = {this.bindValue}> 子: <input onChange={this.props.onChange}> 这样的话,子--->父 传递便实现了
constructor可以初始化state
父: bindValue = (e) => { console.log(e)} <Son onChange = {this.bindValue}> 子: <input onChange={this.props.onChange}> 这样的话,子--->父 传递便实现了
取得state的值,通过 this.state.date
改变state,通过 this.setState({}),不要忘记里面要使用{}的方式
注意事项
(1)修改方式 // Wrong,页面不会重新渲染 this.state.comment = ‘Hello‘; // Correct this.setState({comment: ‘Hello‘}); (2)更新是异步的,有时候通过setState设置数据后,打印,输出的值是不对的
绑定函数
由于this默认是不会绑定到Es6类中的,有几种方法
constructor中设置
constructor (props) { super(props) this.handleClick = this.handleClick.bind(this) }
使用箭头函数
handClick = () => {this.handClick()} 不要忘记了后面加入(),得让函数运行,这样的话还一传递参数,如下: handClick = (e) => {this.handClick(e)}
控制显示和隐藏的时候可以使用 &&
const show = 1 show === 1 && <div>hello React </div> 这样就可以控制是否显示,可以通过一个事件控制show的值
三元表达式
show ? (<div key=‘1‘> show</div>): (<div key=‘2‘> hidden </div>) 最后加key,因为页面在渲染的时候会利用重复的元素,不是每一个都要重复渲染,加入key 就会认为是不同的元素
标签:== cto author reac ons use info .text col
原文地址:https://www.cnblogs.com/felearn/p/React-kai-fa-shi-hou-zhu-yi-dian.html