我的父组件,基本上是一个表单,有一个子组件,一个带有加载器的覆盖层,只需根据父组件的状态显示。
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/