我有一個啞/無狀態組件,用於只渲染一個窗體,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
組件的情況下解決此警告嗎?
@ andew-li是一個錯字修正.. – aeid
你能解釋一下嗎? – aeid