react基本操作
1.事件绑定
export default class ConditionLoop extends Component {
constructor(props){
super(props)
this.showTitleFun = this.showTitleFun.bind(this)
}
showTitleFun(){
this.setState({
showTitle:false
})
}
render() {
return (
<div>
<button onClick={this.showTitleFun}>不显示title</button>
</div>
)
}
}
2.组件内自定义state修改
constructor(props){
super(props)
this.state={
showTitle:true,
}
this.showTitleFun = this.showTitleFun.bind(this)
}
showTitleFun(){
this.setState({
showTitle:false
})
}
注意:this.setState({})是异步操作
//初始count=0
this.setState({
count:this.state.count+1
},()=>{
console.log(this.state.count,
//'这里是后输出的,因为setState是,异步的'----1
})
console.log(this.state.count,'这里是先输出的')//----0
3.循环渲染
render() {
return (
<div>
<ul>
{
this.state.goods.map(good=>{
return <li key={good.title}>
<span>{good.title}</span>
<span>{good.price}</span>
</li>
})
}
</ul>
</div>
)
}
4.条件渲染
{this.state.showTitle?<h1>{this.props.title}</h1>:null}
4.父子组件传值
//parent
<AddKnow show={showAdd} title='新增知识' {...{ onSubmit, onCancel, onSaveDraft }} />
//child
this.props.show
this.props.title
this.props.onSubmit(data)
import Count from './Count'
export default class App extends Component {
constructor(props){
super(props)
this.state = {
showAdd:1,
arr:[1,2,3]
}
this.onAdd = this.onAdd.bind(this)
this.onReduce = this.onReduce.bind(this)
}
onAdd(){
this.setState({
showAdd:this.state.showAdd+1
})
}
onReduce(){
this.setState({
showAdd:this.state.showAdd-1
})
}
render(){
const { onAdd,onReduce } = this;
const { arr } = this.state;
return (
<div>
{msg}
<Count show={this.showAdd} title='新增知识' {...{onAdd,onReduce,arr}}></Count>
</div>
)
}
}
import React, { Component } from 'react';
class Count extends Component{
render(){
const { onAdd,onReduce,arr} = this.props;
return (
<div>
{
arr.map(item=>{
return <p>{item}</p>
})
}
<button onClick={onAdd}>加</button>
<button onClick={onReduce}>减</button>
</div>
)
}
}