设计具有大型父数据结构的reactjs页面组件的合理方法

时间:2016-09-28 23:59:39

标签: reactjs

我刚刚开始使用reactjs,并试图找出设计组件的正确方法。我得到了组件,道具,状态的概念,但是却用正确的方法设计了层次结构。

我有一个由大对象数组驱动的页面。说

objArr = {
  param1 : value1,
  param2: value2,
  dataArray: [
               { key: "keyvalue", a: "a", b: "b", c: "c" },
                ...
             ]
 }

整个页面都以此为基础。该页面构建了一系列与dataArray对应的UI组件。

现在,每次在UI中单击某些图标时,我想要进行一些更改,并且图标对应于此dataArray上的值。什么是确保在执行UI时更改dataArray值的好方法?反之亦然,UI在dataArray上更改值时会发生变化。

我读过“make components尽可能无状态”,很好 - 然后我如何在父组件级别进行处理并让它流下来?

我不需要代码示例。只需指出构建我的ReactJS代码的方法就可以了,我会找出代码。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以做的是绑定父组件上的方法并将其传递给子容器,如下所示:

// Our 'pages' that we want to be able to interact with
const ComponentWIthButtons = ({handleButtonClick, buttons}) => (
    <div>
        <p>Hey, click one of these</p>
        {buttons.map(button => (
            <div onClick={()=>handleButtonClick(button.name)}>
                {button.text}
            </div>
        ))}
    </div>
)
// The Parent we want to interact with
class App extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            buttons: [
                {
                    name: 'a',
                    text: 'Awesome button'
                },
                {
                    name: 'b',
                    text: 'Beautiful button'
                },
                {
                    name: 'c',
                    text: 'Cool button'
                }
            ]
        }
    }
    // This is what you want to do with the information passed
    handleButtonClick = (name) => {
        // this could be updating this components' state, which
        // would rerender the display component because we pass it
        // our buttons from our state object
        console.log(name)
    };

    render(){
        return <div>
            <h2>Below are some buttons!</h2>
            // If you don't use the syntax above, you will run into
            // errors trying to get a reference to this container through
            // `this`. You can do this.handleButtonClick.bind(this)
            // to get around that
            <ComponentWIthButtons handleButtonClick={this.handleButtonClick} buttons={this.state.buttons} />
        </div>
    }
}