0

indexa.js で React コンテキストを宣言し、App.js で設定されたコンテキスト値に Employee.js でアクセスしようとしています。しかし、それは私がReactに慣れていない価値をレンダリングしていません。私を助けてください。前もって感謝します

//index.js

export const employeeContext = React.createContext();
const AppContextInteration = <App></App>
ReactDOM.render(AppContextInteration, document.getElementById('root'));

//App.js

export class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            EmpId: 1,
            EmpName: 'xxx'
        }
    }

    render() {
        return (
            <div>
                <h1> App Component</h1>
                <p> Employee Id : {this.state.EmpId}</p>
                <employeeContext.Provider value={this.state} >
                     <Employee/>
                </employeeContext.Provider>

            </div>
        )
    }
}
//Employee.js

export class Employee extends React.Component {
    context = employeeContext;
    constructor(props) {
        super(props);
        console.log();
    }
    render() {
        return (
            <div>
                <h1>Employee Component </h1>
                <p> Employee Id  : {this.context.EmpId} </p>
            </div>
        )
    }
}
4

2 に答える 2

0

Context.Consumer を使用できます

<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>

https://reactjs.org/docs/context.html

私は関数コンポーネントを useContext フックで使用することを好みます (これは実装が非常に簡単です)。React フックのチュートリアル (useContext)を参照してください。

于 2020-09-20T21:38:45.707 に答える