gpt4 book ai didi

javascript - 通知父组件子组件的连接状态

转载 作者:行者123 更新时间:2023-12-02 14:20:49 24 4
gpt4 key购买 nike

我正在创建一个使用 React 和 Electron 的应用程序。我正在尝试制作一个打开三个 TCP 套接字并在子项全部连接时呈现它们的组件。大致如下(简化):

export class Device extends Component {
static propTypes = {
port: PropTypes.number.isRequired,
host: PropTypes.string.isRequired
};
render() {
const { port, host, children } = this.props;
return (
<div className="device-mount">
<TCPSocket name="commands" port={port} host={host} />
<TCPSocket name="messages" port={port} host={host} />
<TCPSocket name="routines" port={port} host={host} />
{children}
</div>
);
}
}

TCP 套接字将在 componentDidMount 上调度 CONNECT_ATTEMPT 事件,在成功连接时调度 CONNECTED 事件,在连接成功时调度 DISCONNECTED 事件已关闭。

我发现了一个“不干净”的解决方案,只需创建一个连接事件,该事件将使用单个组件并触发所有事件本身,然后在它们全部连接后绑定(bind)一个 .then 处理程序。然而,这似乎不是很好的做法,因为它不可模块化。

我的目标是当所有这些 TCPSocket 组件触发其 CONNECTED 事件时通知父组件。第一个想到的是child context ,但实际上,我想要相反的方向。

如何向父组件通知多个子组件的状态?

最佳答案

给每个人一个回调,他将用它的名称和状态调用它:

export class Device extends Component {
static propTypes = {
port: PropTypes.number.isRequired,
host: PropTypes.string.isRequired
};

constructor(props, context) {
super(props, context);

this.getTCPSocketStatus = this.getTCPSocketStatus.bind(this);
}

getTCPSocketStatus(name, status) {
// whatever you want to do with the status
}
render() {
const { port, host, children } = this.props;
return (
<div className="device-mount">
<TCPSocket name="commands" port={port} host={host} notifyStatus={ getTCPSocketStatus } />
<TCPSocket name="messages" port={port} host={host} notifyStatus={ getTCPSocketStatus } />
<TCPSocket name="routines" port={port} host={host} notifyStatus={ getTCPSocketStatus } />
{children}
</div>
);
}
}

每个 child 都应该使用回调,例如:

class TCPSocket extends Component {
componentDidMount() {
const { notifyStatus, name } = this.props;
this.props.notifyStatus(name, 'CONNECT_ATTEMPT');
}

// implement other status notifications in the same way
}

关于javascript - 通知父组件子组件的连接状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38660207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com