我想动态地改变按钮的背景色。
如果这是我的镭js样式文件:
button-styles.js
export const styles = {
base: {
backgroundColor: 'red',
}
};button.js
const myStyles = require('./styles/button-styles.js');
@Radium
class MyButton extends Component {
render() {
{/*
How do I tell the button to override the default value
for background color of red, to the props value if it exists,
(and in this scenario it does and is the color green)?
*/}
return (<Button style={ ??? }>Click Me</Button>)
}
}
MyButton.defaultProps = {
btnBg: 'green'
}
MyButton.propTypes = {
btnBg: PropTYpes.string
}(这是关于能量的附则;没有反应-镭标记。)
发布于 2016-01-02 20:36:59
您可以创建styles作为props的一个函数。
Advantage:您不需要使用只分配样式的抓取算法。
button-styles.js
export default props => ({
backgroundColor: props.btnBg
// if you need a default value you could use
// props.btnBg || 'green'
})
// You could even use ES6 object destruction
export default ({btnBg}) => ({
backgroundColor: btnBg
})
button.js
const myStyles = require('./styles/button-styles.js');
@Radium
class MyButton extends Component {
render() {
return <Button style={ myStyles(this.props) }>Click Me</Button>
}
}
MyButton.defaultProps = {
btnBg: 'green'
}
MyButton.propTypes = {
btnBg: PropTypes.string
}
发布于 2015-12-28 16:31:57
不知道这样做是否合适,但这对我有用。 基中的默认属性保持不变,而只有那些在dynamicStyle支柱对象中具有匹配的道具名称的属性才会受到影响。因此,在这个示例中,颜色和fontSize没有受到影响,并且保持在返回设置中,现在只有backgroundColor是绿色的。
更新:
根据Janaka的建议,我使设置是不变的。但我是在fetchBtnStyle方法中这样做的,而不是按照Janaka的想法(即颜色属性)对组件进行硬编码,因为我的理论是,我不知道用户希望更改什么属性;用户可能希望更改颜色、字体大小或背景色。
button-styles.js
const styleValues = {
base: {
fontSize: '1.0em',
color: '#fff',
backgroundColor: 'red',
}
};
module.exports = {
fetchBtnStyle(values) {
const settings = {};
// making the value immutable here <-------------
Object.assign(settings, styleValues.base)
if (values !== undefined) {
Object.assign(settings, values);
}
return settings;
}
};button.js
import btnStyles = require('./styles/button-styles.js');
@Radium
class MyButton extends Component {
render() {
return (
<Button style={ btnStyles.fetchBtnStyle(this.props.dynamicStyle) }>
Click Me
</Button>)
}
}
MyButton.defaultProps = {
dynamicStyle: {
backgroundColor: 'green'
}
}
MyButton.propTypes = {
dynamicStyle: PropTypes.object
}发布于 2015-12-28 17:32:57
样式需要是不可变的,所以您需要像这样在呈现中定义它。
class MyButton extends Component {
render() {
let btnSty = MyStyles.base;
if (this.props.dynamicSty)
btnSty.color = this.props.dynamicSty.color;
else
btnSty.color = MyStyles.base.color;
return (
<Button style={btnSty}>
Click Me
</Button>)
}
}
https://stackoverflow.com/questions/34496087
复制相似问题