在React中,inline styles指定了一个对象,其键是样式名称的camelCased版本。你如何使用道具作为关键值?
E.g:
const {
position
} = this.props;
let triangleStyle = {
borderLeft: '5px solid transparent',
borderRight: '5px solid transparent',
`border${position}`: '5px solid red'
};
function Component() {
return <div style={triangleStyle}></div>;
}
答案 0 :(得分:1)
尝试类似:
const triangleStyleFoo = (position) => ({
borderLeft: '5px solid transparent',
borderRight: '5px solid transparent',
`border${position}`: '5px solid red'
});
function Component() {
const { position } = this.props;
const triangleStyle = this.triangleStyleFoo(position);
return <div style={triangleStyle}></div>;
}
答案 1 :(得分:0)
由于我们正在计算风格的关键值,我们可以:
将所有逻辑放入Component中function Component({ position }) {
const triangleStyle = {
borderLeft: '5px solid transparent'
borderRight: '5px solid transparent',
[`border${position}`]: '5px solid red',
}
return <div style={triangleStyle} />
}
或者,将三角形样式提取到函数
const getTriangleStyle = position => ({
borderLeft: '5px solid transparent'
borderRight: '5px solid transparent',
[`border${position}`]: '5px solid red',
})
function Component({ position }) {
return <div style={getTriangleStyle(position)} />
}
答案 2 :(得分:0)
const {
position
} = this.props;
let triangleStyle = {
borderLeft: '5px solid transparent',
borderRight: '5px solid transparent'
};
triangleStyle[`border${position}`] = '5px solid red'
function Component() {
return <div style={triangleStyle}></div>;
}