1. 程式人生 > 實用技巧 >jsx,react父傳子(Props)

jsx,react父傳子(Props)

父傳遞給子元件資料,單向流動,不能子傳遞給父。(但能操作變相傳值給父元件)

props的傳值,可以是任意的型別。

Props可以設定預設值

HelloMessage.defaultProps = { name:”老陳”,msg:“helloworld” }

注意:props可以傳遞函式,props可以傳遞父元素的函式,就可以去修改父元素的state,從而達到傳遞資料給父元素。

父傳子資料傳遞案例

//在父元素中使用state去控制子元素props的從而達到父元素資料傳遞給子元素

class ParentCom extends React.Component{
    constructor(props){
        super(props)
        
this.state = { isActive:true } this.changeShow = this.changeShow.bind(this) } render(){ return ( <div> <button onClick={this.changeShow}>控制子元素顯示</button> <ChildCom isActive={this.state.isActive} />//this.state.isActive將父元件的資料傳入子元件
</div> ) } changeShow(){ this.setState({ isActive:!this.state.isActive }) } } class ChildCom extends React.Component{ constructor(props){//props中已有父元件的值 super(props) } render(){ let strClass = null; // if(this.props.isActive){//this.props.isActive取父元件的值
// strClass = ' active' // }else{ // strClass = "" // } strClass = this.props.isActive?" active":""; return ( <div className={"content"+strClass}> <h1>我是子元素</h1> </div> ) } } ReactDOM.render( <ParentCom />, document.querySelector("#root") )

來自於b站https://space.bilibili.com/40018594?spm_id_from=333.788.b_765f7570696e666f.2