如何影响React库中的子元素样式?

时间:2016-12-05 19:46:24

标签: reactjs

我正在使用Material-ui Library for React。我试图影响日期选择器的宽度,以便它适合包含它的网格系统。

<DatePicker hintText="Set Date" mode="landscape" style={{width: '100%'}}/>

尝试覆盖根样式只会在渲染元素的其余部分周围放置div,但不会影响实际元素。

这就是我所呈现的:(简化)

<div style="width="100%";">
    <div style="width="256px">
        <input>
    </div>
</div>

如何影响像这样的库中的嵌套元素?

2 个答案:

答案 0 :(得分:1)

这取决于库的实现。一般来说,对于广泛使用的图书馆,可以获得不错的文档。

要回答您的特定用例,代码也可用于material-ui datepicker(https://github.com/callemall/material-ui/blob/master/src/DatePicker/DatePicker.js)。正如您在此处所看到的,它接受了一个&#39; className&#39;属性并将其附加到组件中的根div。

<DatePicker hintText="Set Date" mode="landscape" className='full-width'/>

.full-width {
  width: 100%
}

请注意,它还接受样式属性并将其添加到根div。

我认为你实际上想要将它添加到内部文本字段中,为此&#34; textFieldStyle&#34;是财产。或者&#34; dialogContainerStyle&#34;如果是日期选择器容器。但是,我认为你从代码中得到了它的要点。

答案 1 :(得分:0)

如果您正在使用React Component并且想要影响子元素样式,那么您应该确保将样式作为prop传递给父组件并将其应用于子组件。

父元素如下: - <Parent childStyle={styleObject} />

Parent的渲染功能如下: -

render(){ return (<Child style ={this.props.styleObject} />); }