gpt4 book ai didi

javascript - 从父到子 react 使用引用

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:39:34 25 4
gpt4 key购买 nike

我在 react.js 中使用 jqwidget for grid。我的 JqxListBox 在我的父组件中有一个选项列表。

class ParentComponent extends React.Component {
constructor(props) {
super(props);
}

render() {
return <JqxListBox ref='myListBox' style={{ float: 'left' }} width={150} height={150} source={listBoxSource} checkboxes={true} />;
}
}

当用户在 jqxlistbox 中选择或取消选择某些选项时,我想在网格中打开显示和隐藏列,但在子组件中未访问 refs。如何访问子组件 react 中的 jqxlistbox 属性。在子 componentDidMount 函数中,我正在访问 ref。

class ChildComponent extends React.Component {
constructor(props) {
super(props);
}

componentDidMount() {
// Cannot read property 'on' of undefined
this.refs.myListBox.on('checkChange', (event) => {
console.log("something");
});
}

render() {
return <div>Child component</div>;
}
}

它给我错误:TypeError: Cannot read property 'on' of undefined

最佳答案

他们访问refs的方式在 React 16.3.2 中已更改:

这是你应该设置的方式:

class ChildComponent extends React.Component {
constructor(props) {
super(props);
// Declare and initialize the ref in the constructor
this.myListBox= React.createRef();
}

componentDidMount() {
// Access the ref
this.myListBox.on('checkChange', (event) => {
this.props.onEventFromParentComponent(event);
});
}

render() {
return <JqxListBox ref={this.myListBox} style={{ float: 'left' }} width={150} height={150} source={listBoxSource} checkboxes={true} />;
}
}

关于javascript - 从父到子 react 使用引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50014840/

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