【问题标题】:React passing state to sibling component将状态传递给兄弟组件
【发布时间】:2018-01-27 15:07:23
【问题描述】:
const ChatBox = ({ messages, sendInput }) => {
    <Card fluid className={theme} raised style={{ height: '100%' }}>
        <ChatLog
            messages={messages}
        />

         <RecordInput // has internal recording state
           sendInput={sendInput}
         />
    </Card>
}

我的ChatBox 包含ChatLogRecordInput

ChatLog 包含要显示的消息列表。

RecordInput 是要发送到ChatLog 的用户录音输入。该组件有一个内部recording 状态,可以是truefalse

我想将此recording 状态发送到作为兄弟组件的ChatLog

一种解决方案:我可以将ChatBox 设为具有recording 状态的类组件并将其传递给ChatLogRecordInput .. 但我宁愿不重构我的无功能无状态组件..

还有其他方法可以做到这一点吗?也许是 redux 或进行某种克隆?

【问题讨论】:

    标签: javascript reactjs components state


    【解决方案1】:

    有多种选择:

    1. 正如您已经提到的,使用 redux 拥有全局状态。
    2. 添加RecordInputonRecordStatusChange 属性,每次状态更改时都会在该组件内调用该属性,它会告诉父组件(Card)录制的新状态。这样,您可以在父组件和子组件中保存录制状态,并且父组件可以将此数据传递给其他子组件(RecordInput 组件的兄弟姐妹)。
    3. RecordInput 上使用ref 来检查该组件内部的录制状态(我认为这不是您在这种特定情况下想要的,但您可以这样做)。

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 2021-11-19
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多