为了账号安全,请及时绑定邮箱和手机立即绑定

让孩子使用父母传递的功能的问题

让孩子使用父母传递的功能的问题

茅侃侃 2022-10-13 16:21:04
我试图在子类中设置一个按钮,在我的父类上使用 setState。但是,它不起作用,我不确定为什么。当我单击按钮时,我收到一个类型错误,说它无法读取未定义的属性“道具”。这是我的父母代码,我省略了不相关的代码:onButtonClick() {      this.setState({showingLoadingScreen: false})  }//unrelated code betweenrender() {    return (    <div>      <header className="App-header">        <Loading visible={this.state.showingLoadingScreen} onButtonClick={this.onButtonClick} />      </header>      <Map//unrelated code between这是我给孩子的代码,按钮代码标有注释://import statementsconst 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>        ) 
查看完整描述

2 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

问题是this。您需要像这样在构造函数中绑定函数:

this.onButtonClick= this.onButtonClick.bind(this)

更多关于这里https://reactjs.org/docs/handling-events.html


查看完整回答
反对 回复 2022-10-13
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

onButtonClick()在子组件中是不必要的,您可以直接将道具功能传递给按钮

<button onClick={this.props.onButtonClick}>Continue</button>


查看完整回答
反对 回复 2022-10-13
  • 2 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信