Nic*_*rum 8 javascript reactjs
我正在努力了解如何在更高阶的组件中正确实现此验证行为.
===========================================
编辑:TLDR:感谢用户@noa-dev的出色建议,我在这里创建了一个React Fiddle:https://jsfiddle.net/8nLumb74/1/ 来显示问题.
我究竟做错了什么?
文本框组件:
import React from 'react'
export default React.createClass({
changeText(e) {
if (this.props.validate)
this.props.validate(e.target.value)
this.props.update(e.target.value)
},
componentDidMount() {
console.log('should only be fired once')
},
render() {
return (<input type="text"
value={this.props.text}
onChange={this.changeText} />)
}
})
Run Code Online (Sandbox Code Playgroud)
Validator组件:
import React from 'react'
export default function (WrappedComponent) {
const Validation = React.createClass({
validate(text) {
console.log('validating', text)
},
render() {
return (
<WrappedComponent
{...this.props}
validate={this.validate}
/>
)
}
})
return Validation
}
Run Code Online (Sandbox Code Playgroud)
父表单组件:
import React from 'react'
import TextBox from './text-box'
import Validator from './validator'
export default React.createClass({
getInitialState() {
return ({text: 'oh hai'})
},
update(text) {
this.setState({text})
},
render() {
const ValidatingTextBox = Validator(TextBox)
return (<ValidatingTextBox
text={this.state.text}
update={this.update} />)
}
})
Run Code Online (Sandbox Code Playgroud)
Dav*_*yon 10
在组件的render
方法中Form
,您ValidatingTextBox
每次都创建一个新的:
render() {
const ValidatingTextBox = Validator(TextBox)
return (<ValidatingTextBox
text={this.state.text}
update={this.update} />)
}
Run Code Online (Sandbox Code Playgroud)
相反,您应该创建组件然后使用它,以便维护实例.可能的Form
组件如下所示:
import React from 'react'
import TextBox from './text-box'
import Validator from './validator'
const ValidatingTextBox = Validator(TextBox)
export default React.createClass({
getInitialState() {
return ({text: 'oh hai'})
},
update(text) {
this.setState({text})
},
render() {
return (<ValidatingTextBox
text={this.state.text}
update={this.update} />)
}
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2882 次 |
最近记录: |