2017-07-07 47 views
0

這是我第一次嘗試使用React構建。我通常使用jQuery或普通的老式JS編寫UI交互。我只是想要一個文本字段,當有文本輸入時,它會添加一個類,以便我可以將其設置爲與默認狀態不同。注意我只希望在輸入至少一個字符時添加此類,而不是字段集中時添加。父組件狀態改變時向子組件添加一個類

我已經在子組件中使用onChange函數來修改'textEntered'的狀態,但我無法弄清楚如何在子組件中使用這個狀態來添加一個類。

這裏是我的父組件

import React, { Component } from 'react'; 
import ReactDOM from 'react-dom'; 
import TextInput from './components/TextInput/TextInput'; 

export default class Form extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     textEntered: '', 
     completed: false, 
    }; 
    } 

    render() { 
    return (
     <div> 
     <TextInput 
      placeholderText={'Title'} 
      updateText={textEntered => this.setState({ textEntered })} 
      completed={this.state.completed} 
     /> 
     </div> 
    ); 
    } 
} 

ReactDOM.render(<Form />, document.getElementById('react-create-form')); 

這裏是子組件

import React, { PropTypes } from 'react'; 

const TextInput = props => (
    <div> 
    <input 
     type={props.type} 
     placeholder={props.placeholderText} 
     onChange={e => props.updateText(e.target.value)} 
     data-completed={props.completed} 
    /> 
    </div> 
); 

TextInput.propTypes = { 
    type: PropTypes.string, 
    placeholderText: PropTypes.string, 
    updateText: PropTypes.func, 
    completed: PropTypes.bool, 
}; 

TextInput.defaultProps = { 
    type: 'text', 
}; 

export default TextInput; 
+0

結帳https://github.com/JedWatson/classnames –

回答

1

通行證從父組件類的名稱,並且還穿上了檢查。如果文本字段至少包含一個字符,則傳遞實際的類名稱,否則爲空字符串。

既然你存儲文本字段內父組件的狀態值,以便把這樣的條件:

customClass = {this.state.textEntered.length ? 'actualClassName': ''} 

代碼:

<div> 
    <TextInput 
     customClass={this.state.textEntered.length ? 'actualClassName': ''} 
     placeholderText={'Title'} 
     updateText={textEntered => this.setState({ textEntered })} 
     completed={this.state.completed} 
    /> 
</div> 

內部子組件應用此customClass。

const TextInput = props => (
    <div> 
     <input 
      type={props.type} 
      className={props.customClass} 
      placeholder={props.placeholderText} 
      onChange={e => props.updateText(e.target.value)} 
      data-completed={props.completed} 
     /> 
    </div> 
); 

注:另一種方式是,通過在道具,而不是通過類名的值,並直接放子組件中的條件。

+0

這是完美的,謝謝Mayank!由於我是React新手,你會推薦你使用代碼示例的建議方式,還是你在**註釋中建議的方式:**標題? – GuerillaRadio

+0

@GuerillaRadio都幾乎相同,我們需要傳遞任何一個值,無論是類名還是輸入值,但我過去比較喜歡代碼示例,因爲通過這種方式,父對所有事情都負責(處理),它會使孩子更有趣可重複使用。讓我們說在其他地方你想要兩個不同的樣式在孩子那麼你不需要做任何改變的孩子只是從父組件傳遞不同的類名,希望這會幫助你:) –

相關問題