reactjsの同じdivで複数の独立した条件付きスタイルを使用する方法を知りたいです。1つの条件として、三項演算子を使用できます。しかし、私は異なる独立した条件を使用したいと思います。
例:テキストエリアがあり、太字、斜体、下線付きの3つのボタンがあります。いずれかのボタンをクリックすると、それぞれのタスクを実行したいと思います。
これは正常に機能しています
<textarea
onChange={this.handleChange}
style={ this.state.bold ? {fontWeight: 'bolder'} : {fontStyle:
'normal'}}
/>
しかし、これはそうではありません:
<textarea
onChange={this.handleChange}
style={ this.state.bold ? {fontWeight: 'bolder'} : {fontWeight:
'normal'}}
style={ this.state.italic? {fontStyle: 'italic'} : {fontStyle:
'normal'}}
/>
reactjsで複数の独立した条件付きスタイルを持つ方法は?
1つのdivに2つのスタイルを追加することはできません。おそらく良い選択ではないかもしれません。styleとclassNameの両方を使用できます。
style={ this.state.bold ? {fontWeight: 'bolder'} : {fontWeight:
'normal'}}
className={ this.state.italic? {fontStyle: 'italic'} : {fontStyle:
'normal'}}
そして、これを試すこともできます:
setStyle (){
let styles = {}
if (this.state.first === 'first'){
const firstStyle = {
...
}
styles = Object.assign(styles,firstStyle)
}
if (this.state.second === 'second'){
const secondStyle = {
...
}
styles = Object.assign(styles,secondStyle)
}
if (this.state.third === 'third'){
const thirdStyle = {
...
}
styles = Object.assign(styles,thirdStyle)
}
return styles
}
....
<div style={this.setStyle()}>Test</div>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加