reactjs - 根据父状态动态渲染React组件

标签 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>
    );
  }
}

我怎样才能实现这一目标?

我试过React.cloneElement(<Overlay />, {})但我不知道如何将这个 child 重新附加到 parent ,据我所知,这不是做事的 react 方式......

我还尝试设置 prop OB Overlay基于state父级的,例如 React.cloneElement(<Overlay />, { visible = this.state.loading })但似乎无法让它工作......

最佳答案

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

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

记住不要错过渲染函数中的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>
     );
  }
}
<小时/>

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

三元运算符:

速记

render() {
  return condition === someCondition ? <CompA /> : <CompB />;
}

普通手写

render() {
  if ( condition === someCondition ) {
    return <CompA />;
  } else {
    return <CompB />;
  }
}

bool AND 运算符 &&:

速记

render() {
  return condition === someCondition && <CompA />;
}

普通手写

render() {
  if ( condition === someCondition ) {
    return <CompA />;
  } else {
    return null;
  }
}

关于reactjs - 根据父状态动态渲染React组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39703913/

相关文章:

javascript - React+Jest - 测试异步组件并等待挂载

node.js - 将 nodejs 应用程序部署到 heroku 时遇到问题

reactjs - Ant Design 按钮组件禁用时如何更改其文本颜色?

javascript - 如何在 React 中使用新的 Feature Hooks?

ReactJS:如何找到依赖项,仍然通过主 react 包使用 PropTypes

javascript - 谁能帮我分离世博会应用程序

javascript - 如何限制 Electron 应用程序的复制到一定的字长?

reactjs - React-Table 中的固定列

node.js - Socket.io断开与组件的连接不起作用

reactjs - Reactstrap:防止在选择项目时关闭下拉菜单