ReactJS根据子组件更改按钮的可见性

时间:2018-05-14 19:31:49

标签: reactjs visibility setstate react-routing

我在ReactJS中有项目,因为我有3种不同的视图来显示数据。 为此,我有3个不同的组件。

我有一个父组件,其中有一个名为Rotate的按钮和三个选项两个更改视图。

我的要求是我需要根据视图类型设置“旋转”按钮的可见性,例如ViewType1旋转按钮应该是可见的,而对于其他类型的视图,旋转按钮应该是隐藏的。

以下是我的代码:

父组件

class ParentView extends Component {
  constructor(props) {
    super(props);

    this.state = {
       isViewType1: true
    };
    this.setRotateButtonVisibility = this.setRotateButtonVisibility.bind(this);
}
setRotateButtonVisibility(isType1) {
   this.setState({isViewType1 : isType1});
}
render() {
   return(
     {this.state.isViewType1 && (
        <button id="btnRotate" className="btn btn-default">Rotate</button>)
     }
   <Switch>
          <Route
            exact
            path="/project/:projectID"
            render={() => (
            <Viewtype1/>
            )}
          />

          <Route
            exact
            path="/project/:projectID/ukeyview"
            render={() => (
              <Viewtype2/>
            )}
          />
          <Route
            exact
            path="/project/:projectID/proxystructureview"
            render={() => (
              <Viewtype3/>
            )}
          />

     </Switch>
 )}

那么,如何根据视图类型调用setRotateButtonVisibility()函数?

OR

如何根据视图类型设置状态?

我已尝试过子组件的callBackFunc,但它不允许更改状态。

我也尝试过以下代码:

<Route 
   exact
   path="/project/:view
   {...this.setRotateButtonVisibility(false)}
   render={() => (
     <Viewtype3/>
   )}
/>

但没有任何工作正常。

1 个答案:

答案 0 :(得分:0)

您可以使用render()的{​​{1}}方法将该功能传递给孩子。

Route

这意味着可以使用props <Route exact path="/project/:projectId render={() => ( <Viewtype1 setRotateButtonVisibility={(isType1) => this.setRotateButtonVisibility(isType1)} /> )} />

在子反应组件中访问该方法

您需要将组件名称的定义大写。因此,请使用this.props.setRotateVisibility(false)而不是Viewtype1,否则React会认为它是HTML标记而不是组件。请参阅此帖子:ReactJS component names must begin with capital letters?

相关问题