反应组件 - 父子交互;组件生命周期 [英] react component - parent child interaction; component Lifecycle

查看:53
本文介绍了反应组件 - 父子交互;组件生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的浏览器应用程序来从用户那里获取一些特定数据.我有几个组件来简化收集数据的过程,但我目前正在重新考虑渲染这个组件的方式.

基本上,我有我的主要组件,它使用状态来跟踪要渲染的组件.

我几乎对所有组件都这样做.此外,我在父组件中还有一个函数,我通过 props 传递给子组件,当该组件不再有用时,它用作回调将子状态传递给其父组件.

class Main 扩展了 React.Component {构造函数(道具){this.state = {渲染A:真,渲染B:假,子状态:空}}收集状态(状态){this.setState({childState:状态});}使成为() {让内容=空;if(this.state.renderA === true){content = <ComponentA/>} 别的 {content = <ComponentB/>}返回(<div>{内容}

);}}

所以,使用上面的例子,孩子会是这样的

class ComponentA 扩展 React.Component {构造函数(道具){超级(道具);this.state = {停止:假,有用信息:空}破坏() {this.props.collectstate(this.state.usefullInfo)}使成为(){渲染一些东西(比如一个表单),直到 this.state.usefullInfo 被设置;在这种情况下,设置 this.state.stop true 这将调用销毁,将有用的信息传递给父级}}

所以,这种方法对我有用,但我可以清楚地看到,这很可能不是这样做的方法.

此时我的问题是:

1) 如何停止渲染组件而不必使用 this.state.stop 之类的属性跟踪它?

2) 如果我想渲染 2 个不同的组件,就像在主组件中一样,我是否总是必须保持 renderA 和 renderB 属性处于状态,才能渲染一个或另一个?

3) 有没有更好的方法将信息从孩子传递给父母?我目前正在使用通过 props 从父级传递给子级的回调函数,并且当组件完成其目的时我正在调用该回调

4) 关于如何提高上述代码质量的一般建议?

谢谢你的帮助:)!

解决方案

您的示例工作正常,但在 React 中,建议在处理来自多个子项的数据时提升状态(来源).所以我建议保持父级中每个子级的状态,并将带有值和处理程序的 props 传递给子级.

这是您可以查看的示例应用.表单组件处理您要实现的情况.

回答您的问题:

  1. 父组件应该根据自己的状态决定是否渲染子组件.
  2. 不需要将变量保持在关于要呈现的组件的状态.应该在 render() 中根据父级的状态计算
  3. 是的,回调是向父母传递信息的推荐方式
  4. 代码质量看起来不错.使用 prettier 或 ESlint 等工具总是可以做得很好.

这是一个例子:

class Main 扩展了 React.Component {构造函数(道具){this.state = {状态A:'',状态B:'',};}handleStateChange(名称,值){this.setState({[名称]:值,});}使成为() {const { stateA, stateB } = this.statel;const shouldRenderA = !stateA;如果(应该渲染A){return this.handleStateChange('stateA', value)}/>;}return this.handleStateChange('stateB', value)}/>;}}类 ComponentA 扩展了 React.Component {使成为() {const { value, onChange } = this.props;return <input type="text" value="value" onChange={onChange}/>;}}

I am developing a simple browser app to get some specific data from the user. I have several components to simplify the proccess of collecting that data, but I am currently rethinking my way of rendering this component.

Basically, i have my main component, which uses state to keep track of which component to render.

I am doing this for almost all of my components. Also, i also have a function inside the parent component, that i pass to the child component via props, and that is used as a callback to pass the child state to its parent, when that component is no longer useful.

class Main extends React.Component {
  constructor(props){
     this.state = {
        renderA: true,
        renderB: false,
        childState: null
     }
  }

  collectState(state){
      this.setState({
         childState: state
     });
  }

  render() {
     let content = null;
     if(this.state.renderA === true){
         content = <ComponentA />
     } else {
         content = <ComponentB />
     }
     return(
      <div>
         {content}
      </div>);
   }
}

So, using the above example, the child would be something like this

class ComponentA extends React.Component {
   constructor(props){
     super(props);
     this.state = {
        stop: false,
        usefullInfo: null
     }

   destroy() {
      this.props.collectstate(this.state.usefullInfo)
   }

   render(){
    render something (like a Form) untill this.state.usefullInfo is set;
    in that case, set this.state.stop true which will call destroy, passing the usefull information to parent
   }
}

So, this method works for me, but i can see clearly that most probably this is not the way to do this.

At this point my question are:

1) how can I stop rendering a component without having to track it with some property like this.state.stop ?

2) if i want to render 2 different components, like in the main component, do I always have to keep a renderA and renderB property on state, to render one or another?

3) is there a better way to pass information from child to parent? i am currently using a callback function passed via props from parent to child, and i am invoking that callback when the component has done its purpose

4) any general suggestions on how to improve the quality of the above code?

Thank you for you help :)!

解决方案

Your example works fine, but in React it is recommended to lift state up when handling data from multiple children (source). So I would recommend to keep the sate of every children in the parent, and pass props with values and handlers to the children.

Here's a sample app you can check. The form components handle the case you want to implement.

To answer your questions:

  1. The parent component should decide, based on its own state, whether to render a child component or not.
  2. It's not needed to keep variables on state about what component to render. that should be computed in render() based on the parent's state
  3. Yes, callback are the recommended way to pass information to parents
  4. Code quality looks good. You can always do good with tools like prettier or ESlint.

Here's an example:

class Main extends React.Component {
  constructor(props) {
    this.state = {
      stateA: '',
      stateB: '',
    };
  }

  handleStateChange(name, value) {
    this.setState({
      [name]: value,
    });
  }

  render() {
    const { stateA, stateB } = this.statel;

    const shouldRenderA = !stateA;

    if (shouldRenderA) {
      return <ComponentA value={stateA} onChange={value => this.handleStateChange('stateA', value)} />;
    }
    return <ComponentB value={stateA} onChange={value => this.handleStateChange('stateB', value)} />;
  }
}

class ComponentA extends React.Component {
  render() {
    const { value, onChange } = this.props;

    return <input type="text" value="value" onChange={onChange} />;
  }
}

这篇关于反应组件 - 父子交互;组件生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆