使用react时,我会根据用户导航到的路线在页面上更改组件,有没有办法检测当前是否显示组件?
例如,当用户位于不是主页的任何页面上时,将显示“转到主页”按钮,但是当用户导航回到主页时,我想将其删除(它不是那么简单,但是那是大概的概念)

最佳答案

我假设您的按钮已经是子组件,如果它们已经传递给事件处理程序。也许是时候充实一下它们了。

class GoHome extends React.Component {
  constructor(props) {
    super(props);
  }
  state = {
    visible: "shown"
  }
  // While the code here would execute just prior to render,
  // which I assume would happen during page load and after url change,
  // you could place it in a function the serves as a callback
  // to any route change event.
  componentWillMount = () => {
    // Please check this regex.
    var re = /\/home/i;
    if (re.test(window.location.href)) {
      this.setState({
        visible: "not-shown"
      });
    };
  }
  // Using Google's Material Icons as an example.
  render () {
    let myClass = "material-icons " + {this.state.visible};
    return (
      <i className={myClass}>home</i>
    )
  }
}

CSS类。
.shown {
  display: block; // Or inline-block, what-have-you.
}

.not-shown {
  display: none;
}

本质上,该按钮的CSS类将根据当前浏览器URL而有所不同。

关于javascript - React-我可以找出一个组件当前是否可见,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36708202/

10-16 23:11