【问题标题】:Share volatile variable between React Components [duplicate]在 React 组件之间共享 volatile 变量 [重复]
【发布时间】:2020-03-14 07:59:08
【问题描述】:

我有一组组件可以呈现同一页面的不同部分。每当其中一个动作被提交时,其他动作都应该被锁定(应该通过它们传播一个 volatile 标志并触发一个禁用所有元素的 javascript 函数)

块组件:

class FirstBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    render() {......}
}
class SecondBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    render() {......}
}

页面组件:

import FirstBlock from 'Components/FirstBlock';
import SecondBlock from 'Components/SecondBlock';

class PageBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    render() {
        return (
            <FirstBlock ... />
            <SecondBlock ... />
        );
    }
}

有什么想法吗?我是新手,任何提示都会有所帮助。

【问题讨论】:

  • 如果你的组件渲染在不同的地方,你可以看看 Redux (redux.js.org),它为你提供了一种在组件之间共享状态的简洁方式。

标签: javascript reactjs state


【解决方案1】:

在(非常)一般的术语中,将事件处理程序从您的父级传递到您的每个块中。当其中一个触发动作时,请在父级中处理此问题。如果您需要根据哪个孩子提出动作来改变您的行为,您需要为每个孩子设置某种标识符,以便在调用处理程序时它知道要做什么。

class PageBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    onAction = (id)=>{
       // set isVolatile or do whatever you need to do
    }
    render() {
        return (
            <FirstBlock id={firstBlockId} onAction={this.onAction}... />
            <SecondBlock id={secondBlockId} onAction={this.onAction}... />
        );
    }
}


class FirstBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    onAction = ()=>{
        this.props.onAction(this.props.id)
    }
    render() {......}
}

原则是将您的公共状态(即某事已触发动作)提升到父级,以便需要了解该状态的子级可以访问它。

【讨论】:

  • 做到了!谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
  • 2018-09-07
  • 2022-10-12
  • 2014-06-29
相关资源
最近更新 更多