我做了个导航,调用了两重子级组件,父级App组件里面的getkey参数要等于第2级Home子组件定义的menuKey的值[1]。该如何写呢?(这是我删除内容后仅仅为了实现getkey等于menuKey值的内容,为了方便看懂)
import React, { Component } from 'react';
import $ from 'jquery';
import logo from './logo.svg';
import './App.css';
import './style.less';
import Roster from './Roster.js';
import Schedule from './Schedule.js';
import { Switch, Route, Link } from 'react-router-dom';
class Main extends Component {//第1级子组件(路由导航)
render() {
return (
<Switch>
<Route exact path='/' component={Home} />
</Switch>
)
}
}
class Home extends Component {//第2级子组件
render() {
const menuKey = [1];//第2级子组件定义的值,App父级组件要用这个值
return (
<div>
<b>第2级子组件</b>
</div>
)
}
}
class App extends Component {//导航和内容组合App组件
render() {
return (
<div>
<p getkey={'第二级子组件定义的值menukey'}></p>
<Main />
</div>
);
}
}
export default App;
这是未精简的代码
import React, { Component } from 'react';
import $ from 'jquery';
import { Layout, Menu, Dropdown, Breadcrumb, Upload, Icon, Modal, Affix, Button, Steps, AutoComplete, Checkbox, DatePicker, message, Rate, Radio, Select, Carousel, Progress, Spin, BackTop } from 'antd';
import logo from './logo.svg';
import './App.css';
import './style.less';
import Roster from './Roster.js';
import Schedule from './Schedule.js';
import { Switch, Route, Link } from 'react-router-dom';
const { Header, Content, Footer, Sider } = Layout;
const SubMenu = Menu.SubMenu;
class Main extends Component {//第1级子组件
render() {
return (
<Switch>
<Route exact path='/' component={Home} />
<Route path='/roster' component={Roster} />
<Route path='/schedule' component={Schedule} />
</Switch>
)
}
}
class Home extends Component {//第2级子组件
render() {
const menuKey = [1];//第2级子组件定义的值,App组件要用这个值
return (
<Content style={{ margin: '0 16px' }}>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>User</Breadcrumb.Item>
<Breadcrumb.Item>Home</Breadcrumb.Item>
</Breadcrumb>
<div style={{ padding: 24, background: '#fff', minHeight: 360 }}>
Home
</div>
</Content >
)
}
}
class App extends Component {//导航和内容组合App组件
render() {
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider collapsible>
<Menu theme="dark" mode="inline" defaultSelectedKeys={'第二级子组件定义的值menukey'}>
<Menu.Item key="1">
<Link to='/'></Link>
<Icon type="user" />
<span>Home</span>
</Menu.Item>
<Menu.Item key="2">
<Link to='/roster'></Link>
<Icon type="video-camera" />
<span>Roster</span>
</Menu.Item>
<Menu.Item key="3">
<Link to='/schedule'></Link>
<Icon type="upload" />
<span>Schedule</span>
</Menu.Item>
</Menu>
</Sider>
<Layout>
<Header style={{ background: '#fff', padding: 0 }} />
{/* Main组件 */}
<Main menuKey={this.menuKey} />
<Footer style={{ textAlign: 'center' }}>
底部
</Footer>
</Layout>
<BackTop />
</Layout>
);
}
}
export default App;
1.首先你这个值需要在父组件里定义,然后传给子组件,这样父组件才能知道这个值
2.另外修改这个值的方法通过props传给子组件,当子组件需要修改这个值的时候调用父组件传入的方法