新手學習筆記

父組件向子組件傳遞屬性的方法教程講了, 使用this.props, 懶得說函數

從教程推斷props是該組件的屬性集合,this

var Hello = React.createClass({
    render: function() {
        return(
        <div>
        hello, {this.props.name}
        </div>
        );
   }
});

React.render(
<Hello name = "Jack" />,
document.getElementById('box')
);

以上代碼會輸出"hello, Jack" , 不知道想法對不對反正能用,,code

在父組件內添加子組件的時候給子組件添加屬性, 能夠添加一個函數,, 而後在子組件內使用this.props調用這個函數教程

使用傳遞參數的形式來傳遞值get

var Box = React.createClass({
    //初始化屬性
    getInitialState: function() {
        return{data: []};
    },
    //修改屬性
    changed: function(news) {
        this.setState({data: news});
    },
    render: function() {
        return(
        <div>
        <Hello data = this.state.data change = {this.changed} />
        {this.state.data.length}
        </div>
        );
   }
});

var Hello = React.createClass({
    //點擊的時候獲取父組件的屬性, 修改且上傳
    onClick: function() {
        var news = this.props.data;
        news.push(0);
        this.props.change(news);
    },
    render: function() {
        return(
        <div className = "hello" onClick = {this.onClick}/>
        );
    }
});

上面的代碼會在每次點擊子組件時給父組件的data屬性添加一個值, 最後要注意的一點是調用父組件的函數並非在當前組件內運行,,是在父組件內運行,,我也不知道緣由,,猜想是對函數進行了綁定it

相關文章
相關標籤/搜索