简体   繁体   English

如何使用 React 中子组件的 state 更新父组件?

[英]How to update parent's component using state from child component in React?

I have 3 components.我有 3 个组件。

In ListCard.js, I map cards array and based on the card the user click on, I call handleChangeCardData to update the modal's text.在 ListCard.js 中,我使用 map 卡片数组,并根据用户点击的卡片,调用 handleChangeCardData 来更新模态文本。

My question is: How do I update/change the modal's text when my handleChangeCardData function is inside ListCard.js and my modal is on the same level.我的问题是:当我的 handleChangeCardData function 在 ListCard.js 内并且我的模式处于同一级别时,如何更新/更改模式的文本。 (Both are in Board.js) (两者都在 Board.js 中)

Board.js Board.js

const [cardTitle, setCardTitle] = useState("");
return (
     {columns.map((column, index) => (
            <div className="column__container" key={index}>
              <div className="column__header">
                <div className="columnHeader__name">
                  <p>{column.name ? column.name : "..."}</p>
                </div>
                <div className="columnHeader__button">
                  <button
                    className="btn btn-sm --create-card-btn"
                    data-bs-toggle="modal"
                    data-bs-target="#modal-card"
                    onClick={() => setColumnId(column.id)}
                  >
                    New item
                  </button>
                </div>
              </div>
              <Droppable droppableId={column.id}>
                {(provided, snapshot) => (
                  <div
                    className="column"
                    ref={provided.innerRef}
                    {...provided.droppableProps}
                  >
                    <ListCard columnId={column.id} />
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </div>
          ))}
    <ViewCardModal cardTitle={cardTitle} />
)

LisCard.js LisCard.js

const handleChangeCardData = (cardTitle) => {
    setCardTitle(cardTitle);
  }

return (
{cards.map((card, index) => (
        <>
        <div key={index}>
          <Draggable draggableId={card.id} index={index}>
            {(provided, snapshot) => (
              <div
                ref={provided.innerRef}
                {...provided.draggableProps}
                {...provided.dragHandleProps}
              >
                <div
                  className="card --listcard-card"
                  onClick={() => handleChangeCardData(card.title)}
                  data-bs-toggle="modal"
                  data-bs-target="#modal-card-details"
                  style={{ border: `2px solid ${card.color}` }}
                >
                  <div className="card-body">
                    <p>{card.title}</p>
                  </div>
                </div>
              </div>
            )}
          </Draggable>
        </div>
        </>
      ))}
)

ViewCardModal.js ViewCardModal.js

function ViewCardModal(props) {
    return (
        <div>{props.cardTitle}</div>
    )
}

In general, lift state up .通常, 将 state 向上提起 In this case, it sounds like that means moving the state into Board and then passing that state to whatever child components need it (as a prop), and the state setter to whatever (other) child components need it.在这种情况下,这听起来意味着将 state 移动到Board中,然后将该 state 传递给需要它的任何子组件(作为道具),并将 state 设置器传递给任何需要它的子组件(其他)

Here's a minimal example of lifting state up.这是提升 state 的最小示例。 I haven't tried to recreate the full complexity of your example, just to provide an example of Parent having state that ChildA uses and ChildB sets:我没有尝试重新创建您的示例的全部复杂性,只是为了提供一个Parent的示例,该示例具有ChildA使用的ChildB和 ChildB 集:

 const {useState} = React; const ChildA = React.memo(({counter}) => { console.log("ChildA rendered"); return <div>Counter = {counter}</div>; }); const ChildB = React.memo(({setCounter}) => { console.log("ChildB rendered"); return <input type="button" value="Increment Counter" onClick={() => setCounter(c => c + 1)} />; }); const Parent = () => { const [counter, setCounter] = useState(0); return ( <div> <ChildA counter={counter} /> <ChildB setCounter={setCounter} /> </div> ); }; ReactDOM.render(<Parent />, document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.development.js"></script>

If there are several levels of hierarchy between where the state is being held and a descendant component that needs it, you might use context instead of props (although you might also look at component composition instead).如果在持有 state 的位置和需要它的后代组件之间存在多个层次结构,您可以使用上下文而不是道具(尽管您也可以查看组件组合)。 See those links for details.有关详细信息,请参阅这些链接。

you cant do that directly, but must use props.你不能直接这样做,但必须使用道具。

in list:在列表中:

onClick={() => props.onClick(card.title)}

in board:在船上:

 handleChangeCardData = (cardTitle) => {
    setCardTitle(cardTitle);
  }

<ListCard columnId={column.id}  onClick={(e)=>handleChangeCardData(e)}/>

Inside ListCard:列表卡内部:

const ListCard = ({setCardTitle}) => {...}

onClick={() => setCardTitle(card.title)}

In the parent:在父级中:

<ListCard columnId={column.id}  setCardTitle={setCardTitle} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM