根据父状态动态渲染react组件

afk*_*tja 2 reactjs

我的父组件,基本上是一个表单,有一个子组件,一个带有加载程序的覆盖层,它只需要根据父组件的状态显示。

import React from 'react';
import Overlay from './overlay';

export default class RegisterForm extends React.Component {
  constructor {
    this.state = {
      loading: false
    };
  }
  handleSubmit(){
    this.state.loading = true;
    ...
  }

  render(){
    return(
    <form onSubmit={() => this.handleSubmit()}>
     ...
     <Overlay />
    </form>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

我试过了,React.cloneElement(<Overlay />, {})但我不知道如何将这个孩子重新附加到父母身上,据我所知,这不是 React 的做事方式......

我还尝试根据父对象设置propob ,例如但似乎无法使其正常工作...OverlaystateReact.cloneElement(<Overlay />, { visible = this.state.loading })

Sea*_*son 5

对于所讨论的情况,我更喜欢下面的表达式而不是三元运算符

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      { this.state.loading == false && <Overlay /> }
    </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

记住不要错过渲染函数中的return子句。记住不要直接通过赋值来改变状态。这是一个通过单击按钮提交表单并显示加载消息的工作组件。这是实现行为的典型 React 方式。

class HelloWidget extends React.Component{
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this)
    this.state = {
      loading: false
     };
  }
  handleSubmit() {
    this.setState({ loading: true });
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        { this.state.loading && <div>loading...</div> }
        <button>click</button>
       </form>
     );
  }
}
Run Code Online (Sandbox Code Playgroud)

附录 - 以下是两个速记技巧。

三元运算符:

速记

render() {
  return condition === someCondition ? <CompA /> : <CompB />;
}
Run Code Online (Sandbox Code Playgroud)

长手

render() {
  if ( condition === someCondition ) {
    return <CompA />;
  } else {
    return <CompB />;
  }
}
Run Code Online (Sandbox Code Playgroud)

布尔 AND 运算符 &&:

速记

render() {
  return condition === someCondition && <CompA />;
}
Run Code Online (Sandbox Code Playgroud)

长手

render() {
  if ( condition === someCondition ) {
    return <CompA />;
  } else {
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)