使用react时,我的页面上的组件会根据用户导航的路径而变化,有没有办法检测组件当前是否显示? 例如,当用户在任何不是主页的页面上时,"回家"按钮将显示,但我想在用户导航回主页时删除它(它不是那么简单,但这是一般的想法)
答案 0 :(得分:0)
我假设您的按钮已经是子组件,如果它们已经传递了事件处理程序。也许是时候把它们充实了。
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。