首页 文章

ReactJS Component决定使用props或state进行渲染

提问于
浏览
1

我有一个子组件表,每当状态发生变化时都需要渲染,而且,当新的道具从父级到达时,需要进行渲染 .

Table组件应该是可重用的并处理它自己的状态 . 当它的宽度改变时,我使用setState(newTableWidth)重新渲染表(到目前为止,这么好) .

父应用程序Project是创建Table组件并传递初始宽度的应用程序 .

The problem: 在父应用程序(或不同的子组件)中发生更改时,我想更新props.tableWidth并重新呈现Table . 但是在其他情况下,Project会在不更新props.tableWidth的情况下呈现Table .

Table如何知道何时使用props渲染自身以及何时使用状态渲染自身?

代码示例:

class Table extends React.Component {
   constructor(props) {
        this.state = {
           tableWidth: this.props.tableWidth
           columnOrder
       };
    }
   onWidthChange(newWidth){
     this.setState({tableWidth:newWidth})
   }

}

class Project extends React.Component {
 render(){
   if (this.onChangeTableWidth()){
      let width = this.calculateTableWidth();
   }
   <Table tableWidth = {width}/>
 }
}

2 回答

  • 1

    如果父组件决定将新道具传递给子组件,则子组件必须遵守 . 如果道具和州之间存在冲突,只需道具胜利,州需要重置 . 我想一个全局状态就是解决了这个问题,但我从你的问题中了解到你将一些状态封装在子组件中 . 据此,如果父组件想要带来包含维护当前子组件的道具的道具,它可以询问子组件并重塑道具 .

  • 0

    当道具或状态发生变化时,React会自动重新渲染,因此您不必担心这一点 . 您可以使用componentWillReceiveProps(nextProps)生命周期方法使用通过道具收到的新宽度更新您的状态,只需使用 setState(...) 即可 .

相关问题