javascript - 让孩子使用父母传递的功能的问题
问题描述
我试图在子类中设置一个按钮,在我的父类上使用 setState。但是,它不起作用,我不确定为什么。当我单击按钮时,我收到一个类型错误,说它无法读取未定义的属性“道具”。
这是我的父母代码,我省略了不相关的代码:
onButtonClick() {
this.setState({showingLoadingScreen: false})
}
//unrelated code between
render() {
return (
<div>
<header className="App-header">
<Loading visible={this.state.showingLoadingScreen} onButtonClick={this.onButtonClick} />
</header>
<Map
//unrelated code between
这是我给孩子的代码,按钮代码标有注释:
//import statements
const defaultOptions = {
loop: true,
autoplay: true,
animationData: loaderData.default,
rendererSettings: {
preserveAspectRatio: "xMidYMid slice"
}
};
const defaultOptions2 = {
loop: false,
autoplay: true,
animationData: doneData.default,
rendererSettings: {
preserveAspectRatio: "xMidYMid slice"
}
};
export default class Loading extends Component {
constructor(props) {
super(props);
this.state = {
done: undefined
};
}
onButtonClick() {
this.props.onButtonClick();
}
//button code
componentDidMount() {
setTimeout(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(json => {
this.setState({ loading: true });
setTimeout(() => {
this.setState({ done: true });
}, 1000);
});
}, 2000);
}
render() {
return (
<div>
{!this.state.done ? (
<FadeIn>
<div class="d-flex justify-content-center align-items-center">
<h1>Rendering Data</h1>
{!this.state.loading ? (
<Lottie options={defaultOptions} height={120} width={120} />
) : (
<Lottie options={defaultOptions2} height={120} width={120} />
)}
</div>
</FadeIn>
) : (
<div>
<FadeIn transitionDuration = {1000}><h1>Disclaimer</h1></FadeIn>
<FadeIn transitionDuration = {1000}><p>Disclaiming</p></FadeIn>
<button onClick={this.onButtonClick}>Continue</button>
//button code
</div>
)}
</div>
);
}
}
解决方案
问题是this
。您需要像这样在构造函数中绑定函数:
this.onButtonClick= this.onButtonClick.bind(this)
推荐阅读
- reactjs - 如何在地图 react-google-maps 上加载多个标记
- python - 根据一行中的条件将列表拆分为列表
- css - 在带有自定义插件的自定义表单的滑块旋转中使用简码时,CSS 不起作用
- android - andorid kotlin - 如何向下转换合成视图导入
- python - Django JsonField 到表单
- javascript - 如何使用“browser.runtime.sendMessage()”方法?
- redux - 如何调试 react-admin graphql redux 应用程序
- authorization - 复杂的XACML,包的组合和依赖
- php - 在一个网址中强制使用 http,wordpress 网站
- laravel - 如何从 Vue-Tables-2、Vue Js 和 Laravel 做服务器端 PDF