Assume that I want to create a customized button using react. And I'd like to have this component accept color as its properties and render itself based on the color from the properties.
class MyButton extends React.Component {
constructor(props) {
super(props);
}
render() {
const { name, color } = this.props;
return (
<div className="my-button">
<button type="button" className="btn">
{name}
</button>
</div>
);
}
}
How can I inject the color
into the button css style (border and font color)?
Use something like:
EDIT: Added code for border color too
class MyButton extends React.Component {
constructor(props) {
super(props);
}
render() {
const { name, color } = this.props;
return (
<div className="my-button">
<button type="button" className="btn"
style={{
color,
borderColor:color
}}>
{name}
</button>
</div>
);
}
}
Try not to use inline css. Its better to have a class
.btn-primary: {
color: blue;
}
And here is your button.
class MyButton extends React.Component {
constructor(props) {
super(props);
}
render() {
const { name, classNameProp } = this.props;
return (
<div className="my-button">
<button type="button" className={"btn "+ (classNameProp ? classNameProp : '')}>
{name}
</button>
</div>
);
}
}
And you use it like this.
<MyButton classNameProp="btn-primary"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.