创建后是否可以为React组件添加样式?

3
所以,我有一个React组件<Bore />。我有一个Bores数组,我需要为该数组的第一个和最后一个元素设置样式。我知道如何通过Bores [0]Bores [Bores.length-1]访问这些元素。但我的问题是如何在创建后为这些特定组件设置样式。我需要像className +=“newClass”这样做吗?我只使用React 2天,所以任何帮助都将不胜感激。

1
你可以传递一个 prop 给它们。 - Oliver Charlesworth
1
使用 :first-child:last-child - Daniel A. White
当然,这些都是我没有想到的简单事情。感谢您的帮助!哈哈 - jacksons123
1个回答

3

您可以使用样式对象而不是修改类列表。重要的是记住CSS属性是驼峰式命名。例如:

class Parent extends Component {
    constructor(props){
        super(props);
        this.state = { 
            style: {
                backgroundColor: "green",
                marginRight: "10px"
            }
        } 
    }
    changeStyle = () => {
        this.setState(() => {
            return {
                style: {
                    marginLeft: "10px",
                    backgroundColor: "red"
                }
            }
        })
    }
    render = () => {
        return (
            <div>
                <Child style={this.state.style} changeStyle={this.changeStyle}
            </div>
        )
    }
}

const Child = ({ style, changeStyle }) => {
    return (
        <div style={style} onClick={changeStyle}>
          <h1>Dummy</h1>
        </div>
    )
}

点击这里,单击 div 以更改其背景颜色和边距。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接