this.setState是异步调用,所以有个回调函数,等setSate处理完会走回调函数
shouldComponentUpdate 这个方法是当props或者state状态改变时调用
componentWillUpdate:在组件接手到新的props或者state,但是render还没有调用时调用
componentDidUpdate:在组件完成更新后立即调用。在初始化时不被调用
render:页面渲染函数
componentWillUnmount:组件从DOM中移除时立即调用。(当页面离开时调用)
constructor() {
super();
this.state = {
name: '张三',
age: 20
}
}
changeName(mName) {
this.setState({
name: mName,
age: 23
}, () => {
console.log("回调函数:" + this.state.name)
});
console.log("是否改变姓名:" + this.state.name);
}
render() {
var name = "<span style='color: #FF0000;'>张三</span>";
return (
<div>
<div>我是从state传递过来的,姓名是{this.state.name},年龄是{this.state.age}</div>
<button onClick={this.changeName.bind(this,"王五")} type="button">改变年龄</button>
</div>
)
}
}
双向绑定
export default class EventComponet extends Component {
constructor() {
super();
this.state={
sText:""
}
}
render() {
return (
<div>
<input onChange={(e) => {
console.log(e.target.value);
this.setState({
sText:e.target.value
})
}}/>
<div>{this.state.sText}</div>
</div>
)
}
}
全选和反选
export default class EventComponet extends Component {
constructor() {
super();
this.state = {
sText: "",
list: [
{id: "1", title: "新闻标题1", checked: false},
{id: "2", title: "新闻标题2", checked: false},
{id: "3", title: "新闻标题3", checked: false},
{id: "4", title: "新闻标题4", checked: false},
{id: "5", title: "新闻标题5", checked: false},
{id: "6", title: "新闻标题6", checked: false},
{id: "7", title: "新闻标题7", checked: false},
{id: "8", title: "新闻标题8", checked: false},
]
}
}
handleChecked(e, index) {
let tList = this.state.list;
tList[index].checked = e.target.checked;
this.setState({
list: tList
});
console.log("itemOncheck", JSON.stringify(this.state.list));
}
allChecked(e) {
if (e.target.checked) {
let aList = this.state.list;
if (aList.length > 0) {
for (let i = 0; i < aList.length; i++) {
aList[i].checked = true;
}
this.setState({list:aList},()=>{
console.log("allChecked",this.state.list)
});
}
} else {
let aList = this.state.list;
if (aList.length > 0) {
for (let i = 0; i < aList.length; i++) {
aList[i].checked = false;
}
this.setState({list:aList},()=>{
console.log("allChecked",this.state.list)
});
}
}
}
render() {
return (
<div>
<input onChange={(e) => {
console.log(e.target.value);
this.setState({
sText: e.target.value
})
}}/>
<div>{this.state.sText}</div>
<div><input type='checkbox' onClick={this.allChecked.bind(this)}/>全选和反选</div>
<div>
<ul>
{
this.state.list.map(
(item, index) => {
return (
<li key={index}>
<label><input type='checkbox' checked={item.checked?'checked':''} onClick={(e) => {
this.handleChecked(e, index)
}}/>{item.title}</label>
</li>
)
}
)
}
</ul>
</div>
<button type="button">提交</button>
</div>
)
}
}