2016-05-13 468 views
0

我試圖算出這個工作,我不知道爲什麼這不工作默認值發生反應,在流星

<input type="text" id="first_name" name="first_name" className="form-control" defaultValue={this.props.user.first_name} required/> 

但這個工程

<input type="text" id="first_name" name="first_name" className="form-control" value={this.props.user.first_name} required/> 

不同的是valuedefaultValue,如果我使用的值該字段變爲只讀,並使用defaultValue不會打印任何東西。

我正在使用與流星發生反應。我試圖在return語句之前的呈現方法中嘗試記錄this.props.user並打印該對象。

+0

你想在現場展示什麼? –

回答

1

當您將this.props.user.first_name分配給value屬性時,並不是輸入字段變爲只讀,而是您從不處理該值發生更改時發生的情況。 React只是用每次直接分配給它的值重新渲染它。

如果您希望使字段可編輯且具有默認的用戶名值,您應該維護並瞭解輸入的狀態。

因此,例如:

// Initialize some component state in either your constructor or getInitialState function 
constructor(props){ 
    super(props);  

    this.state = {userInput: this.props.user.first_name}; 
} 


// Have a function that updates state when your input changes 
onInputChange(event) { 
    this.setState({ userInput: event.target.value }); 
} 


// Then set the value equal to your userInput state and add an onChange 
// prop to the input tag in your render method. 
render() { 
    return (
    ... 
    <input 
    type="text" 
    id="first_name" 
    name="first_name" 
    className="form-control" 
    value={this.state.userInput} 
    onChange={this.onInputChange.bind(this)} /> 
) 
} 

然後該字段的值初始化爲它正在通過this.props.user.first_name所提供的價值,同時還保持編輯。

編輯:

正如在評論中指出,雖然有效,這實際上是在反應的反模式。由於子組件的初始狀態只被調用一次,因此從父項到子項的值的更改不會導致子項的狀態發生任何變化。如果用例明確地設置了一個你不想要的或者期望在組件生命週期中改變的初始值(儘管那時它不是一個好的模式),但是如果你確實希望初始值是可變的你有兩個選擇。

選項一:將狀態置於父組件中,它可能屬於它。然後,子組件應該接收並渲染髮送它的任何道具。初始值的更改在父組件狀態下處理,道具被視爲不可變,並且所有內容都保持同步。

方案二:如果因任何原因,你都需要從道具確定狀態,你還指望那些道具改變,你可以使用componentWillReceiveProps(nextProps)生命週期的方法來保持同步的一切。這將允許你檢查this.propsnextProps並進行任何狀態變化,如果他們是必要的:

componentWillReceiveProps(nextProps) { 
    if(nextProps.user.first_name !== this.props.user.first_name){ 
    this.setState({ 
     userInput: nextProps.user.first_name 
    }); 
    } 
} 

這裏給DOCS鏈接以備將來參考。

+0

感謝一堆兄弟! – mdanishs

+0

這是錯誤的!您正在使用組件自己的狀態對道具進行靜音,因此如果有來自父組件的更新,則此組件將不會更新。這在React中被認爲是反模式https://medium.com/@justintulk/react-anti-patterns-props-in-initial-state-28687846cc2e#。1fcw0u473 –

+1

@ThaiTran很好地回答了一個老問題,我已經更新了答案,以更好地闡明這是一種反模式,並添加了其他一些可以採用的方法。 –