Javascript 由父级传递子级使用函数时出现问题

Javascript 由父级传递子级使用函数时出现问题,javascript,reactjs,Javascript,Reactjs,我试图在子类中有一个按钮,在父类中使用setState。然而,它不起作用,我不确定为什么。当我点击按钮时,我收到一个typeerror,表示它无法读取undefined的属性“props”。 这是我的家长代码,我省略了不相关的代码: onButtonClick() { this.setState({showingLoadingScreen: false}) } //unrelated code between render() { return ( <di

我试图在子类中有一个按钮,在父类中使用setState。然而,它不起作用,我不确定为什么。当我点击按钮时,我收到一个typeerror,表示它无法读取undefined的属性“props”。

这是我的家长代码,我省略了不相关的代码:

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.onButtonClick= this.onButtonClick.bind(this)
更多信息请参见这里的按钮点击子组件是不必要的,您可以直接将道具功能传递给按钮

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

我改了。现在我有另一个错误,即无法读取未定义的属性setState。从父级中的onButtonClick函数。你知道问题是什么吗?你需要约束它。阅读我提供的文件,一切都会清楚。这是否回答了你的问题?