我的目标是做一个简单的开放和关闭菜单的反应。我习惯于,在这里我可以使用getElementById获取元素并将它们存储在变量中,并随它们执行任何我想做的事情。现在我试着用它来做反应,但是它变得有点模糊,我已经尝试使用ref。
所以这是我的菜单,我想点击按钮,隐藏菜单并显示内容,这是我的目标。
import React, { Component } from 'react';
import { Grid, Row, Col } from 'react-flexbox-grid';
class Menu extends Component {
render() {
function handleClick(e) {
var mobileContainer = this.refs.mobileContent1;
console.log(mobileContainer);
}
return (
<Grid fluid>
<div className="menuContent">
<Row center="xs">
<Col xs={12}>
<span href="" className="button" onClick={handleClick}>Hello, world!</span>
</Col>
</Row>
</div>
</Grid>
);
}
}
export default Menu;当我控制台日志mobileContainer时,我得到了,这是未定义的
这是我的内容组件
import React, { Component } from 'react';
import { Grid, Row, Col } from 'react-flexbox-grid';
class MobileContent extends Component {
render() {
return (
<Grid fluid>
<div className="mobileContent" ref="mobileContent1">
<Row center="xs">
<Col xs={12}>
<span className="button">Hello, world!</span>
<span className="close">X</span>
</Col>
</Row>
</div>
</Grid>
);
}
}
export default MobileContent;谢谢你的帮助
发布于 2017-10-05 13:20:42
首先,不应该在handleClick函数中定义单击处理程序render,只要调用render,就会一次又一次地创建它。
现在出现错误的原因是您还没有将函数bind到this。
将您的代码更改为这样的代码。
class Menu extends Component {
constructor (props) {
super(props);
// bind the handler
this.handleClick = this.handleClick.bind(this);
}
// you should define your function here
handleClick() {
...
}
render(){
.....
}
}发布于 2017-10-05 13:17:35
我建议您使用组件的内部状态来修改菜单,而不是使用ref
class Menu extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.setState(function(prevState){
return {isOpen: !prevState.isOpen}
});
// Passing in a function into setState instead of an object will give you a reliable value for your component’s state and props.
}
render() {
return (
<Grid fluid>
<div className="menuContent">
<Row center="xs">
<Col xs={12}>
<span href="" className="button" onClick={handleClick}>Hello, world!</span>
<MobileContent isOpen={this.state.isOpen} />
</Col>
</Row>
</div>
</Grid>
);
}
}
class MobileContent extends Component {
render() {
if (this.props.isOpen) {
return (
<Grid fluid>
<div className="mobileContent" ref="mobileContent1">
<Row center="xs">
<Col xs={12}>
<span className="button">Hello, world!</span>
<span className="close">X</span>
</Col>
</Row>
</div>
</Grid>
);
}
return null;
}
}
export default MobileContent;基本上,使用state来检查是否需要呈现某些内容。这只是基本的,你可以用它做任何你想做的事:添加动画,重新组织你的代码等等。
在React中,数据流下降,组件可以选择将其状态作为支持传递给其子组件。
你必须以反应而不是jQuery的方式思考。查看此页面:https://reactjs.org/docs/thinking-in-react.html
希望它有帮助:)
https://stackoverflow.com/questions/46586050
复制相似问题