【发布时间】: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