【问题标题】:how to add dynamic css in react js如何在 React js 中添加动态 CSS
【发布时间】:2018-10-20 17:51:31
【问题描述】:

我们可以在 React js style={style} 中实现这一点吗??

constructor(props) {
   super(props);
   this.state = {
     style_title: {"color": "blue"}
   };
 this.change = this.change.bind(this);
}

change(e) { 
 this.setState({ 
   [e.target.name]: e.target.value }) 
}

我的表单

<input type="text" name="title" value={this.props.title} onChange={e =>this.changeEdit(e)} /> 
<input type="text" name="style_title" value={this.props.style_title} onChange={e =>this.changeEdit(e)} />  

在预览模式下打印标题文本为此我需要使用输入字段动态设置标题样式,例如:

{ "color": "blue", "font-size": "22px",} 

以上样式应在样式属性中应用渲染&lt;p style={style}&gt;{this.props.title }&lt;/p&gt;

预览部分

render = () => (
 const style = this.props.style_title; 

 return (
     <p style={style}>{this.props.title }</p>
 );
)

【问题讨论】:

  • 你的问题需要解释你写的更多,你的愿望有点不清楚,你的意思是,你想要一个表单来获取样式并将其实现到另一个组件?
  • 是的,一旦我点击提交值应该更新 this.state {title:"",custom_css:""}

标签: reactjs


【解决方案1】:

React 中,您可以通过传递此处提到的对象来传递动态样式: React.js inline style best practices

或者你也可以像这样传递内联:

<div style={{ height: '10%' }}>
  Hello World!
</div>

请注意,css 属性将位于 camelCase 中,例如borderBottom: '10px'

【讨论】:

  • 我需要添加自定义 css 作为用户输入表单字段来设置文本样式
  • 在这种情况下,您需要将表单输入值作为对象保存到组件state。然后在您的render() 方法中,您需要或应该在所需区域/位置使用state 值,例如this.state.myStyleProp1 等。
  • 是的,但前提是style_title 持有对象并且只是字符串值。例如this.state = {style_title: {height: '20px', width: '90px'}}那么你就可以按照你说的方式使用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多