简体   繁体   English

如何访问 React 容器内的样式对象?

[英]How do I access styles object inside React container?

I'm working on app and I used some ready components from a library.我正在开发应用程序,并且使用了库中的一些现成组件。 There is functional component where inline styles for divs are taken from object included in this component.有一个功能组件,其中 div 的内联样式是从该组件中包含的对象中获取的。

<div style={styles.chatsContainer} className='ce-chats-container'>

and this object is below return function这个对象在返回函数下面

const styles = {
    chatListContainer: {
        maxHeight: '100vh',
        overflow: 'scroll',
        overflowX: 'hidden',
        borderRight: '1px solid #afafaf',
        backgroundColor: 'white',
        fontFamily: 'Avenir'
    },
    chatsContainer: {
        width: '100%',
        height: '440px',
        backgroundColor: 'white',
        borderRadius: '0px 0px 24px 24px'
        
    },
}

My question is - how do I access those values so I can change them with onClick?我的问题是 - 如何访问这些值,以便我可以使用 onClick 更改它们?

I tried changing it like this, didn't work ('values read-only')我试着像这样改变它,没有用('值只读')

styles.chatsContainer.height = "250px !important"

I tried setting state in styles object but there are errors "chatsHeight is not defined"我尝试在样式对象中设置状态,但出现错误“chatsHeight 未定义”

const [chatsHeight, setChatsHeight] = useState("440px")
chatsContainer: {
        width: '100%',
        height: chatsHeight,
        backgroundColor: 'white',
        borderRadius: '0px 0px 24px 24px'
}
    

You can create a separate style for that task:您可以为该任务创建单独的样式:

const styles = {
    chatsContainer: {
        width: '100%',
        height: '440px',
        backgroundColor: 'white',
        borderRadius: '0px 0px 24px 24px' 
    },
    newHeight: {
        height: '250px'
    }
}

and then you can create a state that adds your newHeight style on your div when the state is true;然后你可以创建一个状态,当状态为真时在你的 div 上添加你的 newHeight 样式;

const [add, setadd]= useState(false)

const onClickHandler= ()=>{
setadd(!add)
}

 <div style={`${styles.chatsContainer} ${add && style.newHeight}`} className='ce-chats-container'>

And dont forget to trigger your onClickHandler function.并且不要忘记触发您的 onClickHandler 函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM