react 基礎記錄

1、render 函數 裏面只能用一個標籤

//正確
render () {
    return (<div>hello<div>)
}
//錯誤
render () {
    return (
        <div>hello<div>
        <div>world<div>
    )
}

2、state在組件在的定義、使用、以及改變

  • 定義
//在constructor函數中定義
constructor ( props ) {
    super(props);
    this.state = {
        inputValue:"",
        list:[]
    }
}
  • 使用
<input value = { this.state.inputValue} />
  • 改變
<input value = { this.state.inputValue} onChange = {this.changeInput.bind(this)} />
//方法一
changeInput(e){
    this.setState({
        inputValue:e.target.value
    })
}
//方法二
changeInput(e){
    const value = e.target.value;//需要保存變量,不能在下面直接用e.target.value,或者會報錯
    this.setState(()=>({
        inputValue:value
    }))
}

3、註釋寫法

{/*註釋*/}
//或者
{
//註釋
}

4、css中的class與es6的class衝突,改用className來代替

5、laber標籤和input做關聯是所用的for 要用htmlFor來代替

6、父組件傳值給子組件

//父組件通過屬性的方式傳給子組件
//父組件
<todoList content = {item} />
//子組件接受則用props
//子組件
<div>{this.props.content}</div>

7、子組件像父組件傳參

//父組件通過屬性傳父組件的方法給子組件(注意:必須bind(this),否則子組件this指向有問題)
//父組件
<todoList delete = {this.delete.bind(this)} />
//子組件接受
delete(){
    this.props.delete();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章