2017-09-15 5 views
0

私はそれをクリックした後にdivの背景色を変更するステートフルなコンポーネントを持っています。私は状態でブール値のフラグを保持し、それが変化すると、コンポーネントはその色を再計算し、自身を再レンダリングします。色をどのようにして反応状態にするか?

このブール値フラグを削除するにはどうすればいいですか、色自体を状態に保ちたいのですが、色が変化した状態でコンポーネントが再レンダリングされます。

class App extends React.Component { 
constructor(props) { 
    super(props); 
    this.state = { flag: true }; 
} 
changeColor(){this.setState({flag: !this.state.flag})}; 

render(){ 
var bgColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; 
return (<div style={{backgroundColor: bgColor}} onClick={this.changeColor.bind(this)}>wonderful</div>); 
} 
} 

ReactDOM.render(<App />, document.getElementById('root')); 
+0

ので、状態の文字列を格納します。あなたは何を理解していますか? – SLaks

答えて

1

changeColor機能

var bgColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; 

に移動これは、次いで、例えば、同じchangeColor関数内状態内側bgColorを格納

this.setState({ color: bgColor }); 

class App extends React.Component { 

constructor(props) { 
    super(props); 
    this.state = {color: null}; 
} 

changeColor(){ 
    this.setState({ 
     color: 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + 
     (Math.floor(Math.random() * 256)) + ',' + 
     (Math.floor(Math.random() * 256)) + ')' }) 
    }; 
} 

render(){ 
    return ( 
    <div style={{backgroundColor: this.state.color}} 
     onClick={this.changeColor.bind(this)} 
    > 
     wonderful 
    </div> 
); 
} 
1

、色状態変数作るcomponentDidMount上のカラー機能を使用して、初期の色を計算し、その後、クリック時に再計算します。

class App extends React.Component { 
 
    constructor(props) { 
 
    super(props) 
 
    this.setColor = this.setColor.bind(this) 
 
    this.state = { 
 
     color: null 
 
    } 
 
    } 
 

 
    componentDidMount() { 
 
    this.setColor() 
 
    } 
 

 
    setColor() { 
 
    let newColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')' 
 
    this.setState({color: newColor}) 
 
    } 
 

 
    render() { 
 
    return ( 
 
     <div style={{backgroundColor: this.state.color}} onClick={this.setColor}> 
 
     wonderful 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id='root' />

+0

これは興味深い解決策です。 – kilogram

関連する問題