I have a component that renders perfectly the first time, but no changes to the passed in variables will affect anything, even though passing in true or false for open seems to always work fine. Why doesn't this work?
const ChatWindow = ({ open, prevContent }) => {
var content = prevContent.messages.map(message => (
<Message player={message.player} text={message.text} />));
const openClose = () => {
if(open){
open = false;
} else {
open = true;
}
console.log(open);
}
return (
<div className="ChatWindow">
<div className="openWindow" onClick={() => openClose()}>{open ? "X" : "O"}</div>
<div className="Content">
{content}
</div>
<style jsx>{`
.ChatWindow {
opacity: ${open ? "1.0" : "0.3"};
}
.Content {
max-height: ${open ? "400px" : "0px"};
opacity: ${open ? "1.0" : "
overflow-y: ${open ? "scroll" : "hidden"};
}
`}</style>
</div>
)
}
React responds to changes in the component's state/props, not just a change in any variable. Make your open
property part of the component's state and use setState
to update it.
constructor(props) {
super(props);
this.state = {
open: false,
};
}
You need to cause a re-render on open/close, for that its preferred to maintain a state either in parent of in the current component
class App extends React.Component {
state= {
open: false;
}
openClose = () => {
this.setState(prevState => ({open: !prevState.open}))
}
render() {
const { prevContent } = this.props;
var content = prevContent.messages.map(message => (
<Message player={message.player} text={message.text} />));
const { open } = this.state;
return (
<div className="ChatWindow">
<div className="openWindow" onClick={() => this.openClose()}>{open ? "X" : "O"}</div>
<div className="Content">
{content}
</div>
<style jsx>{`
.ChatWindow {
opacity: ${open ? "1.0" : "0.3"};
}
.Content {
max-height: ${open ? "400px" : "0px"};
opacity: ${open ? "1.0" : "
overflow-y: ${open ? "scroll" : "hidden"};
}
`}</style>
</div>
)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.