我有一个演示。在 HOC 中。
它将做两件事:处理状态并使用refs
处理MyComponent
.
当状态改变时我会遇到问题。
在proc
函数中:instance
将记录两次,值为null
和MyCompenent instance
。并且该值null
是错误的值,但我不知道为什么instance
在proc
函数日志中两次。为什么instance
是null
?你能告诉我为什么吗?
import React from 'react';
import ReactDOM from 'react-dom';
// it's a HOC.
// has manage a state: name
// and!! I have a function: proc, will get MyComponent instance
const MyContainer = (WrappedCompoent) => {
return class extends React.Component {
constructor (props) {
super(props)
this.state = {
name: ""
}
this.onNameChange = this.onNameChange.bind(this)
}
onNameChange (event) {
this.setState({
name: event.target.value
})
}
proc (instance) {
console.log(instance); // when state change, this will process twice. the instance will have two value: null and MyComponent
instance && instance.test()
}
render () {
const newProps = Object.assign({
text: "newText",
name: {
value: this.state.name,
onChange: this.onNameChange
}
}, this.props, {ref: this.proc.bind(this)})
return (
<div>
<WrappedCompoent {...newProps}/>
</div>
)
}
}
}
@MyContainer
class MyComponent extends React.Component {
test () {
console.log(123);
}
render () {
return (
<div>
{this.props.text}
<input name="name" {...this.props.name}/>
</div>
)
}
}
ReactDOM.render(
<div><MyComponent/>123</div>,
document.getElementById('root')
)