简体   繁体   English

如何在 React 中为元素添加样式?

[英]How can I add styling to an element in React?

In normal JavaScript you can grab an element by its id and add a style to it.在普通的 JavaScript 中,您可以通过其 id 获取元素并为其添加样式。 For example:例如:

var element = document.getElementById("myElement");
element.style.backgroundColor = "#f5f5f5";

My question is how you can do this in react.我的问题是你如何在反应中做到这一点。 Is it even possible to add this style?甚至可以添加这种样式吗? In react im using onChange in a function outside the render().在 render() 之外的 function 中使用 onChange 做出反应。 I looked at the React DOM for styling and tried but since styling is in different function it will tell me how the variable is undefined.我查看了 React DOM 的样式并进行了尝试,但由于样式在不同的 function 中,它会告诉我变量是如何未定义的。 this is my code:这是我的代码:

ChangeImage() {
        var imgStyles = {
            backgroundColor: '#000',
            padding: 5,
        }
    }

    render() {
        return (
            <div className="class">
                <div className="img-surround">
                <img 
                    src={this.state.file} 
                    id="img" 
                     style={imgStyles}/>
                </div>

Everything is working except styles and I even tried putting in different functions除了 styles 外,一切正常,我什至尝试放入不同的功能

If you want to render the element with the style you can return the element like this in a react functional component:如果要使用样式呈现元素,可以在反应功能组件中返回这样的元素:

return <div style={{backgroundColor: "#f5f5f5"}}></div>

If you want the element to only have that style in a certain condition you can use the useState hook in a react functional component:如果您希望元素仅在特定条件下具有该样式,则可以在反应功能组件中使用 useState 挂钩:

const [myState, setMyState] = useState(false);
return <div style={myState && {backgroundColor: "f5f5f5"}}></div>

And you should change myState's value using setMyState however you like.你应该使用 setMyState 改变 myState 的值,但是你喜欢。 For example:例如:

const [myState, setMyState] = useState(false);
return <div onClick={() => myState ? setMyState(true) : setMyState(false)} style={myState && {backgroundColor: "f5f5f5"}}></div>

In this example whenever you click on the div the style is added or removed by case在此示例中,每当您单击 div 时,都会按大小写添加或删除样式

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

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