[英]Css inline style as an attribute in React component
I have custom component in which i map attributes. 我有自定义组件,其中我映射属性。 In this component I have label which have css class assigned. 在这个组件中,我有标签,分配了css类。 But i also want optional inline style for this label. 但我也想要这个标签的可选内联样式。 The problem is that in react I need to surround inline style with curly braces and i can't escape them or set them correctly in component. 问题是,在反应中我需要用花括号包围内联样式,我无法逃脱它们或在组件中正确设置它们。 How to resolve this? 怎么解决这个?
Code from component: 组件代码:
const CustomComponent = ({items, name}) => (
<fieldset>
{items
.map((item, index) => ({item, id: `${name || 'dod'}-${item.value || index}`}))
.map(({item, id}) =>
<div key={id}
className="className1">
<input
id={id}
name={name}
type="text"
/>
<label htmlFor={id} className="className" style={item.style}>
{item.label}
</label>
</div>
)}
</fieldset>
);
Code from rendered .jsx 来自渲染的.jsx的代码
<CustomComponent
name="name"
items={[{
value: 'value',
label: 'label',
style: {{display: 'inline'}} -> not working
}]}
/>
Your style property have to be an object literal, something like so : 你的style属性必须是一个对象文字,如下所示:
item.style = {
display: 'inline'
}
在反应中,您可以以JS对象的形式定义样式,例如
style: {{display: 'inline'}}
You only need to include the first {}
when you are directly inside a Virutal DOM Object
. 当您直接进入Virutal DOM Object
时,您只需要包含第一个{}
。 <... items={object} .../>
and then object should be written exactly the same way as other Object Literals
. <... items={object} .../>
然后对象应该与其他Object Literals
文字完全相同。 That being said you need {display: 'inline'}
instead of {{display: 'inline'}}
in 据说你需要{display: 'inline'}
而不是{{display: 'inline'}}
<CustomComponent
name="name"
items={[{
value: 'value',
label: 'label',
style: {{display: 'inline'}} -> not working //use {display: 'inline'}
}]}
/>
I've made a pen for this in Codepen
, you can check it Here . 我已经在Codepen
为此制作了一支笔,你可以在这里查看。
You can abstract this further and have a JS file holding all the styles for your page: 您可以进一步抽象,并拥有一个包含页面所有样式的JS文件:
const styles = {
myElement: {
display: 'inline'
}
}
then in the code... 那么在代码中......
<Component style={styles.myElement} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.