我很反应......
主要布局有一个h1,h2,style.object,所以我需要根据子组件修改它。
更改此主要布局的h1,h2等的最佳方法是什么?
class App extends Component {
render() {
return (
<div className="App" >
<Navbar />
<Main>
{ this.props.children }
</Main>
<Footer />
</div>
)
}
}
&#13;
class Main extends React.Component {
render() {
return (
<div className="Main">
<div className="Header" style={this.props.styles.header}>
<h1 style={ this.props.styles.h1 }>{ this.props.header1 }</h1>
<h2 style={ this.props.styles.h2 }>{ this.props.header2 }</h2>
</div>
<div className="MainContent">
<div className="InnerContent">
{ this.props.children }
</div>
</div>
</div>
)
}
}
&#13;
答案 0 :(得分:0)
this.props.styles
将为this.state.styles
然后
您在updateHeader
中定义了接受新样式并调用Main
的方法setState
} ..
此方法应通过context
然后
孩子会通过this.context.updateHeader(newStyle,..)
class Main extends React.Component {
static childContextTypes = {
updateHeader: React.PropTypes.func
};
updateHeader(styles, header1, header2) {
this.setState({styles, header1, header2})
}
render() {
return (
<div className="Main">
<div className="Header" style={this.state.styles.header}>
<h1 style={ this.state.styles.h1 }>{ this.state.header1 }</h1>
<h2 style={ this.state.styles.h2 }>{ this.state.header2 }</h2>
</div>
<div className="MainContent">
<div className="InnerContent">
{ this.props.children }
</div>
</div>
</div>
)
}
}
支持Something
是Main
个孩子之一:
class Something extends React.Component {
static contextTypes = {
updateHeader: React.PropTypes.func
}; ;
componentDidMount() {
this.context.updateHeader({styles:header:{} , h1:{}, h2{} }, "i am header1", "i am header 2");
}
}