我正在研究一個基本的顏色選擇器應用程序來學習React並對它有更好的理解。反應 - 製作全球可訪問的風格對象
這種工作方式是我有一個接受十六進制值的文本字段,並在鍵入時將它們顯示爲背景色。我想要發生的是,在清除文本字段時,背景會作爲默認值返回到無。現在,它恢復到以前的顏色在鍵入的功能代碼我至今如下:。
class ColorPick extends React.Component {
constructor(props) {
super(props);
this.state = {
color: "Let's pick a color"
};
}
changeColor(event) {
var colorInput = document.getElementById('colorInput').value;
this.setState({
color: event.target.value
});
if (colorInput === '') {
this.setState({
color: "Let's pick a color",
backgroundColor: "#fff"
});
}
}
render() {
var styleObj = {
backgroundColor: this.state.color,
};
return (
<section style={styleObj} id="Profile" >
<h2 className="colorHeader">{this.state.color}</h2>
<input id="colorInput" placeholder="Enter Hex Code Here" onChange={this.changeColor.bind(this)}/>
</section>
);
}
}
ReactDOM.render(<ColorPick />, document.getElementById('app'));
爲了實現對彩色背景與空文本字段清算,我試圖全球化變量/對象styleObj
並將其值更改爲backgroundColor: none
如果該字段的值爲空白。隨着這一點,我宣佈它使用let
。所以,要做到這一點我想:
class ColorPick extends React.Component {
// making styleObj global and changing from var to let.
let styleObj = {
backgroundColor: this.state.color,
};
...
changeColor(event) {
var colorInput = document.getElementById('colorInput').value;
this.setState({
color: event.target.value
});
if (colorInput === '') {
this.setState({
color: "Let's pick a color",
backgroundColor: "#fff"
});
// attempting to reset back to default after text field is cleared
let styleObj = {
backgroundColor: none,
};
}
}
但是,有兩個意想不到的結果發生了:
從頁面製作
styleObj
一個全球性完全消失後的組件對象變量backgroundColor
變成意想不到的標識符。
不應該讓該CSS塊成爲一個全局變量/對象可以訪問整個範圍?我也嘗試更改我的變量的具體位置,從組件創建的正下方到render
方法的正上方。我應該以不同的方式做這件事嗎?
下面是兩個叉,功能版本,並且不與評論工作的版本:
工作版本: https://codepen.io/kawnah/pen/EZqLaq?editors=0010
非工作版本: https://codepen.io/kawnah/pen/XpvOpp?editors=0010
編輯:正如你所看到的,對於我的顏色狀態的佔位符,我使用了一個字符串。期待這個突破,它的工作。爲什麼?
好吧,我看到我做錯了 - 我基本上需要將文本和背景顏色分成兩個單獨的值。所以,如果我可以傳遞一個字符串,反應狀態數據類型並不嚴格?我很驚訝地發現這並沒有打破。 – kawnah
@kawnah,它們並不嚴格,如果你可以傳遞一個字符串在哪裏? React數據類型雖然並不嚴格,但我的意思是React只是javascript。所以數據類型(就像'state'和變量一樣)將會像Javascript那樣寬鬆。 – aaronofleonard