這一切都取決於你想要達到的目標。乍一看,我可以看到2個選項。一個創建一個子組件和兩個:使用redux作爲redux在所有子組件之間提供單一狀態。
第一種選擇:
export default class parentClass extends Component {
state = {
param1: "hello".
};
render() {
return (
<Child param1={this.state.param1}/>
);
}
}
class Child extends Component {
render() {
console.log(this.props.param1);
return (
<h1>{this.props.param1}</h1>
);
}
}
現在上面的子組件將有props.param1
從它通過的父渲染功能道具定義。
上面的工作,但我可以看到你正試圖建立一個'共同'的功能集。選項2通過爲您的應用程序/項目創建單一狀態提供了一種方法。 如果您還沒有使用過redux,那麼一旦掌握了它就很容易使用。我現在要跳過設置http://redux.js.org/docs/basics/UsageWithReact.html。
請減速,像這樣:
import * as config from './config';//I like to make a config file so it's easier to dispatch my actions etc
//const config.state = {param1: null}
//const config.SOME_FUNC = "test/SOME_FUNC";
export default function reducer(state = config.state, action = {}) {
switch(action.type) {
case config.SOME_FUNC:
return Object.assign({}, state, {
param1: action.param1,
});
break;
default:
return state;
}
}
}
是添加到您的減速器爲您的商店。
將所有組件包裝在提供程序中。
ReactDOM.render(
<Provider store={store} key="provider">
<App>
</Provider>,
element
);
現在,您可以在提供程序的所有子組件上使用redux連接!
像這樣:
import React, {Component} from 'react';
import {connect} from 'react-redux';
@connect(
state => (state),
dispatch => ({
someFunc: (param1) => dispatch({type: config.SOME_FUNC, param1: param1}),
})
)
export default class Child extends Component {
eventFunction = (event) => {
//if you wanted to update the store with a value from an input
this.props.someFunc(event.target.value);
}
render() {
return (
<h1>{this.props.test.param1}</h1>
);
}
}
當你習慣了Redux的檢查了這一點https://github.com/redux-saga/redux-saga。這是你的最終目標!薩加斯很棒!如果你陷入困境讓我知道!
您是否嘗試過在你的'someFunc'刪除'export',並把這個功能您'MyComp內'班? – Jacky
@Jacky當然可以工作。但是我在幾個組件中使用'someFunc()'... – Stophface
也許你可以使用HOC來管理你的狀態,並將道具傳遞給你的包裝組件。 https://facebook.github.io/react/docs/higher-order-components.html#use-hocs-for-cross-cutting-concerns –