我有以下内容:
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不是函数“,但是如果我删除withStyles,代码就会正常工作。
我只是将“导出默认的withStyles(样式)(快照)”改为“导出默认值(Snack);”。
为什么它不能正确地与"withStyles“一起工作?我怎么才能让它起作用?
发布于 2018-12-31 16:44:08
因为withStyles封装了组件,所以需要使用:
<Snack innerRef={ref => (this.snack = ref)} />withStyles将innerRef属性作为ref传递给包装组件。
我使用最新版本的@material-ui/core (目前为3.8.1)进行了尝试。我不能保证旧版本也能以同样的方式支持这一点。
下面是一个充分发挥作用的示例:
发布于 2018-12-31 16:45:14
问题在于,因为withStyles自组织返回一个新组件,因此您将获得该临时组件的引用。您可以使用innerRef道具:
<Snack innerRef={ ref => this.snack = ref } />根据正式文件:
它添加了一个innerRef属性,这样您就可以获得对包装组件的引用。innerRef的用法与参考文献相同。
您可以在正式文档这里 withStyle函数中检查它。
我已经用你现在的版本测试过了,它可以正常工作。
https://stackoverflow.com/questions/53989353
复制相似问题