[英]React - passing ref to sibling
我需要有2个兄弟组件,其中1个必须引用另一个 - 这可能吗?
我试过这个:
<button ref="btn">ok</button>
<PopupComponent triggerButton={this.refs.btn} />
甚至这个
<button ref="btn">ok</button>
<PopupComponent getTriggerButton={() => this.refs.btn} />
但是我在两种情况下都undefined
。 有任何想法吗?
注意:父组件对我不起作用,因为我需要有多组,比如
<button />
<PopupComponent />
<button />
<PopupComponent />
<button />
<PopupComponent />
不喜欢这样:
<div>
<button />
<PopupComponent />
</div>
<div>
<button />
<PopupComponent />
</div>
<div>
<button />
<PopupComponent />
</div>
认为这个问题最好由文档回答:
如果您还没有使用React编写多个应用程序,那么您的第一个倾向通常是尝试使用refs在您的应用程序中“让事情发生”。 如果是这种情况,请花一点时间,更关键地考虑组件层次结构中应该拥有状态的位置。 通常,很明显,“拥有”该状态的适当位置在层次结构中处于更高级别。 在那里放置状态通常消除了使用refs“让事情发生”的任何愿望 - 相反,数据流通常会实现你的目标。
不确定你想要做什么,但我的预感是一个父组件,传递道具是你真正想要的。
我完全赞同Mark McKelvy提供的引用。 你想要实现的目标被认为是React中的反模式。
我将补充说,创建父组件并不一定意味着它必须是直接父组件,您可以在链的上方创建一个父组件,在该组件中可以将所有子组件的数组一起呈现,具有逻辑根据你的例子,所有孩子(或一对孩子)之间的协调坐在你父母的内部。
我创建了一个概念的粗略示例,应该可以解决这个问题:
class A extends React.Component {
onClick(key) {
alert(this.refs[key].refs.main.innerText);
}
render() {
var children = [];
for (var i = 0; i < 5; i++)
children.push.apply(children, this.renderPair(i));
return (
<div>
{children}
</div>
);
}
renderPair(key) {
return [
<B ref={'B' + key} key={'B' + key} onClick={this.onClick.bind(this, 'C' + key)}/>,
<C ref={'C' + key} key={'C' + key} onClick={this.onClick.bind(this, 'B' + key)}/>
];
}
}
class B extends React.Component {
render() {
return <p ref="main" onClick={this.props.onClick}>B</p>;
}
}
class C extends React.Component {
render() {
return <p ref="main" onClick={this.props.onClick}>C</p>;
}
}
React.render(<A/>, document.getElementById('container'));
你需要为所有孩子储蓄的任何州,你都是在共同的父母身边。 我真的希望这会有所帮助。
以下代码帮助我设置两个兄弟之间的通信。 设置在render()和componentDidMount()调用期间在其父级中完成。 希望能帮助到你。
class App extends React.Component<IAppProps, IAppState> {
private _navigationPanel: NavigationPanel;
private _mapPanel: MapPanel;
constructor() {
super();
this.state = {};
}
// `componentDidMount()` is called by ReactJS after `render()`
componentDidMount() {
// Pass _mapPanel to _navigationPanel
// It will allow _navigationPanel to call _mapPanel directly
this._navigationPanel.setMapPanel(this._mapPanel);
}
render() {
return (
<div id="appDiv" style={divStyle}>
// `ref=` helps to get reference to a child during rendering
<NavigationPanel ref={(child) => { this._navigationPanel = child; }} />
<MapPanel ref={(child) => { this._mapPanel = child; }} />
</div>
);
}
}
特殊道具警告JSX元素上的大多数道具都传递给组件,但是,React使用了两个特殊道具(ref和key),因此不会转发给组件。
例如,未定义尝试从组件(例如,渲染函数)访问this.props.key。 如果需要在子组件中访问相同的值,则应将其作为不同的prop传递(例如:)。 虽然这似乎是多余的,但将应用程序逻辑与协调提示分开很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.