2017-03-26 60 views
1

我有一個啞/無狀態組件,用於只渲染一個窗體,React無狀態組件與受控的表單元素?

只是一個典型的窗體。

import React from 'react' 

export const AuthorForm = 
({ firstName , lastName , handlefnChange , handlelnChange}) => (
    <form action=""> 
    <h2>Manage Authors</h2> 
    <label htmlFor="firstName">First Name</label> 
    <input type="text" name="firstName" 
     value={firstName} onChange={handlefnChange} /> 
    <br/> 
    <label htmlFor="lastName">Last Name</label> 
    <input type="text" name="lastName" 
     value={lastName} onChange={handlelnChange} /> 
    <br/> 
    <input type="submit" value="save" /> 
    </form> 
) 

我控制從父智能組件

這是剛剛呈現上表單組件傳承 道具值和事件處理這種形式

import React , {Component} from 'react' 
import {AuthorForm} from './' 

export class ManageAuthors extends Component { 
    constructor(){ 
    super() 
    this.state = { 
     author:{ 
     id: "", 
     firstName:"", 
     lastName:"" 
     } 
    } 
    } 

    handlefnChange = e => { 
    this.setState({ 
     author:{ 
     firstName: e.target.value 
     } 
    }) 
    } 

    handlelnChange = e => { 
    this.setState({ 
     author: { 
     lastName: e.target.value 
     } 
    }) 
    } 

    render =() => (
    <div> 
    <AuthorForm 
     {...this.state.author} 
     handlefnChange={this.handlefnChange} 
     handlelnChange={this.handlelnChange} /> 
    </div> 
) 
} 

一切工作正常,但我得到這個警告

warning.js:36 Warning: AuthorForm is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://facebook.github.io/react/docs/forms.html#controlled-components

我可以在不轉換成stateful組件的情況下解決此警告嗎?

+0

@ andew-li是一個錯字修正.. – aeid

+0

你能解釋一下嗎? – aeid

回答

3

這是因爲筆者對象失去或者當您修改其中任何一個的firstNamelastName場:

handlefnChange = e => { 
    this.setState({ 
     author: { 
     firstName: e.target.value 
     // lastName is missing! 
     } 
    }); 
    } 

handlelnChange = e => { 
    this.setState({ 
    author: { 
     // firstName is missing! 
     lastName: e.target.value 
    } 
    }) 
} 

陣營不僅會的this.state頂層合併。由於firstNamelastName嵌套在author對象內,因此當您執行handlefn/lnChange並僅設置其中一個字段時,另一個字段丟失。

的解決將是做:

handlefnChange = e => { 
    this.setState({ 
     author: { 
     firstName: e.target.value, 
     lastName: this.state.author.lastName 
     } 
    }); 
    } 

handlelnChange = e => { 
    this.setState({ 
    author: { 
     firstName: this.state.author.firstName, 
     lastName: e.target.value 
    } 
    }) 
} 

或者,如果你有在未來兩個以上的領域,這將是更容易使用的傳播運營商合併:

handlefnChange = e => { 
    this.setState({ 
    author: { 
     ...this.state.author, 
     firstName: e.target.value, 
    } 
    }); 
} 

handlelnChange = e => { 
    this.setState({ 
    author: { 
     ...this.state.author, 
     lastName: e.target.value 
    } 
    }) 
} 

或者使用來自lodash的實用程序合併功能。

相關問題