在React组件下更改子元素<div>的样式

使用像这样的React组件


const teststyle={color:red}

class Test extends React.Component {

  render() {

        <ParentComponent 

          mainContent={

           <ul>

            <li>1</li>

            <li>2</li>

            <li>3</li>

           </ul>}

         >

         </ParentComponent>

   }

}

该<ParentComponent>会自动生成一个<div>道具标签:maincontent。所以最终的渲染结果是……


    <ParentComponent>

      <div class="testtest">

        <ul>

         <li>1</li>

         <li>2</li>

         <li>3</li>

       </ul>

      </div>

    </ParentComponent>

我在内部定义了测试样式 </ParentComponent>


我试图更改<div>单击列表项时的CSS样式。如何div dom在<ParentComponent>文件中获取和应用样式?


白猪掌柜的
浏览 1409回答 3
3回答

慕尼黑8549860

如果组件自动生成,那么它的道具也可以随之生成,您可以在那里设置样式<div style={this.styleChanger}></div>,然后按照下面的步骤进行操作创建这样的状态state = {&nbsp; styleChange: true}然后执行如下所示的功能。我知道这看起来很丑,但这是给演示的clicker = () => {&nbsp; &nbsp; if (this.state.change) {&nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; styleChange: false&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; backgroundColor: "red"&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; styleChange: true&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; };在这里调用函数onClick并将函数设置为样式,它将自动执行&nbsp; <ParentComponent>&nbsp; &nbsp; &nbsp; <div style={this.styleChanger}>&nbsp; &nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<li onClick={this.clicker}>1</li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<li>2</li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<li>3</li>&nbsp; &nbsp; &nbsp; &nbsp;</ul>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </ParentComponent>

海绵宝宝撒

会自动为道具生成一个标签: maincontent这只会在内部ParentComponent有div周围环境的情况下才会发生<div>&nbsp; &nbsp; {this.props.children}</div>如果是这种情况,则应使用React.Fragment<Fragment>&nbsp; &nbsp; {this.props.children}</Fragment>或者<>&nbsp; &nbsp; {this.props.children}</>因此,只需更改ParentComponent为使用Fragment并以所需的样式添加自己的div元素即可。<ParentComponent>&nbsp; <div style={this.styleChanger}>&nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp;<li onClick={this.clicker}>1</li>&nbsp; &nbsp; &nbsp;<li>2</li>&nbsp; &nbsp; &nbsp;<li>3</li>&nbsp; &nbsp;</ul>&nbsp; </div></ParentComponent>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript