React组件使用redux connect后,如何使用ref去访问组件内部的元素?

Winter

2020-04-26

// CustomControl.jsx
class CustomControl extends Component {
    constructor(props){
        super(props);
    }
    say() {
        console.log("hello");
    }
    render() {
        return <div ref="root"></div>
    }
}
const App = connect(
    mapStateToProps => {return {};},
    mapDispatchToProps => {}
)(CustomControl);
export default App;
// home.jsx
class Home extends Component {
    constructor(props){
        super(props);
    }

    render() {
        return <div ref="root"><CustomControl ref="customControl"/></div>
    }
}

例如这里我们在home.jsx,直接去访问this.refs.customControl.say();是无法访问的。

第4158篇《React组件使用redux connect后,如何使用ref去访问组件内部的元素?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Winter 2020.04.26

conect函数包含四个参数

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

options具体设置如下:

[options] (Object) 如果指定这个参数,可以定制 connector 的行为。

  • [pure = true] (Boolean): 如果为 true,connector 将执行 shouldComponentUpdate 并且浅对比 mergeProps 的结果,避免不必要的更新,前提是当前组件是一个“纯”组件,它不依赖于任何的输入或 state 而只依赖于 props 和 Redux store 的 state。默认值为 true
  • [withRef = false] (Boolean): 如果为 true,connector 会保存一个对被包装组件实例的引用,该引用通过 getWrappedInstance() 方法获得。默认值为 false

 

所以当我们设置了 connect() 函数的第四个参数 options{ withRef: true } 才返回被包装的组件实例。这时候我们就能访问了。

上面的例子将可以通过这样去访问:

this.refs.customControl.say();

更多信息可以了解react-redux中文文档

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android