gpt4 book ai didi

javascript - 已有对象时如何在jsx样式属性中添加变量?

转载 作者:行者123 更新时间:2023-12-05 05:40:16 25 4
gpt4 key购买 nike

我正在尝试通过使用变量名 myStyle 编写逻辑来在 textarea 标记中执行 text-align,所以逻辑有效但是然后当我为黑暗模式制作一个切换开关并添加更多样式作为对象时。然后 myStyle 停止工作。所以问题是,当已经存在给定对象时,如何在 style 属性中添加 myStyle 变量?正确的格式是什么?


export default function TextForm(prop) {
const [text, setText] = useState("Enter text here");

const [myStyle, setMyStyle] = useState({
textAlign:'left'
})
const textAlign = ()=>{
if(myStyle.textAlign === 'left'){
setMyStyle({
textAlign: 'center'
})
}
else if(myStyle.textAlign === 'center'){
setMyStyle({
textAlign:'right'
})
}
else{
setMyStyle({
textAlign:'left'
})
}
}

return (
<>
<div className='container' style={{color: prop.mode==='light'?'Black':'white'}}>
<h2>{prop.heading} </h2>
<div className="mb-3">
<textarea className="form-control " style={myStyle,{ backgroundColor:prop.mode==='light'?'white':'grey', color:prop.mode==='light'?'black':'white'}} value={text} onChange= {handleOnChange} id="myBox" rows="6"></textarea>
</div>
<button className="btn btn-primary mx-1" onClick={textAlign} >Change Text Align</button>
</div>
</>
)
}

最佳答案

将现有对象展开到一个新对象中,并在该新对象中列出所需的附加属性。

<textarea
className="form-control "
style={{
...myStyle,
backgroundColor:prop.mode === 'light' ? 'white' : 'grey',
color: prop.mode === 'light' ? 'black' : 'white'
}}
value={text}
onChange={handleOnChange}
id="myBox"
rows="6"
></textarea>

虽然在元素上切换 CSS 类会更优雅,并且使用 CSS 规则而不是通过 JS 设置的属性来执行此操作。

关于javascript - 已有对象时如何在jsx样式属性中添加变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72442430/

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