首页 文章

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

提问于
浏览
0

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

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

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

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

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

我已经读过“使组件尽可能无状态”,很好 - 那么我如何在父组件级别进行此处理并让它流下来?

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

谢谢

1 回答

  • 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>
        }
    }
    

相关问题