簡體   English   中英

在ReactJS的父組件中設置子組件的prop

[英]Setting a prop of a child component inside a parent component in ReactJS

我正在創建一個分頁表,並且希望能夠自定義行輸出。

看起來像。


  
 
  
  
  
    var PagedTable = React.createClass({


    	propTypes:{
    		'table_headers' : React.PropTypes.array,
    		'table_rows' : React.PropTypes.array
    	},
    	getInitialState: function(){
    		return{
    			pageSize: 10,
    			currentPage: 1
    		}
    	},
    	componentWillReceiveProps: function(nextProps) {
    		this.setState({
    			currentPage: 1
    		})
    	},
    	getPage: function(){
    		var start = this.state.pageSize * (this.state.currentPage - 1);
    		var end = start + this.state.pageSize;

    		return{
    			currentPage: this.state.currentPage,
    			table_rows: this.props.table_rows.slice(start, end),
    			numPages: this.getNumPages(),
    			handleClick: function(pageNum) {
    				return function() {
    					this.handlePageChange(pageNum)
    				}.bind(this)
    			}.bind(this)
    		}	
    	},
    	getNumPages: function() {
    		var numPages = Math.floor(this.props.table_rows.length / this.state.pageSize);
    		if (this.props.table_rows.length % this.state.pageSize > 0){
    			numPages++
    		}
    		return numPages			
    	},
    	handlePageChange: function(pageNum) {
    		this.setState({currentPage: pageNum})
    	},
    	render:function(){
    		var page = this.getPage();
    		var topics = page.table_rows.map(function(row) {
    			return <IncompleteRow row={row}/>
    		});
    		return <div>
    		  <table className="table table-hover table-primary table-bordered colm-freeze">
    		    <PagedRowHeader header_row={this.props.table_headers}/>
    		    {topics}
    		  </table>
    		</div>
    	}
    });

上面的代碼已修改,但高度基於: this


  
 
  
  
  
    <PagedTable>
      <IncompleteRow/>
    </PagedTable>

或喜歡


  
 
  
  
  
    <PagedTable>
      <CompletedRow/>
    </PagedTable>

如你看到的。 現在,我在render方法中設置了不完整的行。 但我想使此組件可擴展。 這意味着我希望能夠呈現不同種類的行。

問題在於要知道要呈現哪些行,我需要進入PagedTable類,因為它知道當前應顯示哪些行。 因此,我的PagedTable需要知道它要呈現哪種類型的行。

我已經嘗試過使用this.props.children,但是我對如何從父組件設置孩子的proptype感到困惑。

也許我對您要完成的工作感到困惑,但是您不能做類似的事情:

var topics = page.table_rows.map(function(row) {
    return row.someFlag ? <CompletedRow row={row}/> : <IncompleteRow row={row}/>;
});

我陷入了如何從父組件設置孩子的原型的問題。

我使用React.ChildrenReact.cloneElement來映射具有父類正確屬性的子元素。

React.Children.map(this.props.children, function (child) {
  return React.cloneElement(child, {
    someProperty: this.props.someProperty
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM