1. 程式人生 > >react 常見api 使用(長期更新)

react 常見api 使用(長期更新)

tar this event con 自定義 方法 inpu struct ...

1、父子通信

1.1 父-子 props

父組件:
    class myPage extends React.Component {
           render() {
                return (
                  <div>
                    {/* 子組件   自定義page 是子組件要接受的屬性   mypage是要傳遞的內容*/}
                    <TabBar page="mypage"></TabBar>
                        <div className="pd-md">
                        我是一個mypage
                      </div>
                  </div>
            );
      }
}
子組件:
class TabBarComponents extends React.Component {
  constructor(props) {
    // 繼承父組件
    super(props);
    this.state = {
    // 接受父組件傳的屬性
      selectedTab: props.page,
    };
  }
// 然後使用 this.state.selectedTab  這個值, 這個就是mypage   
....
}

1.2

子-》父

子組件:將子組件的value值 text 傳遞給父組件

    class Input extends Component {
        changeTitle(event) {
            // 子組件調用 父組件通過props傳遞過來的方法 onChangeText,將要傳遞的值傳見方法
            this.props.onChangeText(event)
        }
        render() {
          return (
            <div className="list-wrapper">
               <input type="text"  onChange={this.changeTitle.bind(this)} value={this.props.text}/>
            </div>
          );
        }    
  }

父組件:


class myPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {newText: 'default'};
  }
  changeText(event) {
    this.setState({
      newText: event.target.value,
    })
  }

  render() {
    return (
      <div>
       <div className="pd-md">
          <h3>我是一個mypage</h3>
          <div>
            {this.state.newText}
            {/* 子組件 */}
            <InputCompenent onChangeText={this.changeText.bind(this)} text={this.state.newText}></InputCompenent>
          </div>
        </div>
        
      </div>
    );
  }
}

子組件通過調用 props.onChangeText 方法,將值傳遞進來,父組件通過 changeText 方法來接受 傳遞進來的值。
套路:子組件通過調用 父組件傳遞的方法 傳值。

react 常見api 使用(長期更新)