【问题标题】:withStyles component wrapwithStyles 组件包装
【发布时间】:2019-05-28 02:21:48
【问题描述】:

我有以下组件:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import Snackbar from '@material-ui/core/Snackbar';

const styles = theme => ({
  error: {
    backgroundColor: theme.palette.error.dark,
  }
})

class Snack extends React.Component {

  state = {
    opendialog: false,
  }

  constructor(props) {
    super(props);
  }

  test() {
    this.setState({opendialog: !this.state.opendialog});
  }

  render() {
    return (
      <Snackbar open={this.state.opendialog}>
        <SnackbarContent message="test"/>
      </Snackbar>
    );
  }
}

export default withStyles(styles)(Snack);

和应用程序主:

import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import logo from './logo.svg';
import './App.css';
import Snack from './Snack.js';

class App extends Component {
  constructor(props) {
    super(props);
    this.snack = React.createRef();
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
            <Button variant="contained" color="primary" onClick={this.handleHello}>Hello World</Button>
            <div>
            <Snack ref={ ref => this.snack = ref } />
            </div>
      </div>
    );
  }
  handleHello = () => {
    this.snack.test();
  }
}

export default App;

当我单击按钮时,我得到一个“TypeError: _this.snack.test is not a function”,但是如果我放弃 withStyles 代码可以正常工作。

我只是替换“export default withStyles(styles)(Snack);”符合“导出默认(Snack);”。

为什么它不能与“withStyles”一起正常工作?我怎样才能让它发挥作用?

【问题讨论】:

  • 您的@material-ui 版本是什么?
  • 当前:“dependencies”:{“@material-ui/core”:“^1.4.3”,“react”:“^16.4.2”,“react-dom”:“^ 16.4.2", "react-scripts": "1.1.4" 我试了几个。

标签: reactjs material-ui


【解决方案1】:

问题是因为withStyles HOC 返回了一个新组件,因此您获得了 HOC 的引用。你可以使用innerRefprop:

<Snack innerRef={ ref => this.snack = ref } />

根据官方文档:

它添加了一个 innerRef 属性,因此您可以获得对包装组件的引用。 innerRef 的用法与 ref 相同。

可以在官方文档herewithStyle函数中查看。

我已经用你当前的版本测试过它可以正常工作

【讨论】:

    【解决方案2】:

    因为withStyles 包装了你的组件,你需要改用:

    <Snack innerRef={ref => (this.snack = ref)} />
    

    withStylesinnerRef 属性作为ref 传递给包装的组件。

    我尝试使用最新版本的@material-ui/core(当前为 3.8.1)。我不能保证旧版本以同样的方式支持这一点。

    这是一个完整的示例:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-20
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 2019-12-03
      • 2019-07-27
      相关资源
      最近更新 更多