gpt4 book ai didi

javascript - React js,为什么当我更改 open 的值时我的组件没有重新渲染?

转载 作者:行者123 更新时间:2023-12-01 02:10:18 25 4
gpt4 key购买 nike

我有一个第一次就完美渲染的组件,但是对传入变量的任何更改都不会影响任何内容,即使为 open 传递 true 或 false 似乎总是工作正常。为什么这不起作用?

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>
)
}

最佳答案

您需要在打开/关闭时重新渲染,因为最好在当前组件的父组件中维持状态

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>
)
}

}

关于javascript - React js,为什么当我更改 open 的值时我的组件没有重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49802928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com