1

我有一个演示。在 HOC 中。
它将做两件事:处理状态并使用refs处理MyComponent.

当状态改变时我会遇到问题。
proc函数中:instance将记录两次,值为nullMyCompenent instance。并且该值null是错误的值,但我不知道为什么instanceproc函数日志中两次。为什么instancenull?你能告诉我为什么吗?

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')
)

4

0 回答 0