React中如何将类组件的state变量传递给其他组件使用
实现步骤
1. 确认Editar2.js的组件导出
首先需要确保Editar2.js末尾导出了EscolheRestaurante组件,否则App.js无法引入调用:
// Editar2.js 末尾添加导出代码 export default EscolheRestaurante;
2. App.js中引入组件并传递参数
在App.js中先引入该组件,再在渲染逻辑里把state中的restaurantes、还有select触发的回调函数作为props传给组件即可:
// App.js 顶部引入组件,路径根据你实际的文件存放位置调整 import EscolheRestaurante from './Editar2'; // 类组件写法示例 class App extends React.Component { constructor(props) { super(props); this.state = { restaurantes: [] // 你的原有state定义 } } // 选中餐厅的处理逻辑,按你自己的需求写 handleRestauranteChange = (e) => { console.log('选中的餐厅ID:', e.target.value); // 你的业务逻辑 } render() { const { restaurantes } = this.state; return ( <div className="App"> {/* 你原有App.js的其他渲染内容 */} <EscolheRestaurante // 传state里的restaurantes,加||[]避免初始值为undefined时map报错 restaurantes={restaurantes || []} // 传选中回调 idRestauranteEscolhido={this.handleRestauranteChange} /> </div> ) } } // 如果你的App是函数组件,写法如下: function App() { const [restaurantes, setRestaurantes] = useState([]); // 你的原有state定义 // 选中餐厅的处理逻辑,按你自己的需求写 const handleRestauranteChange = (e) => { console.log('选中的餐厅ID:', e.target.value); // 你的业务逻辑 } return ( <div className="App"> {/* 你原有App.js的其他渲染内容 */} <EscolheRestaurante restaurantes={restaurantes || []} idRestauranteEscolhido={handleRestauranteChange} /> </div> ) }
可选优化:你也可以在
Editar2.js的map调用处加可选链兼容,写法为props.restaurantes?.map(...),效果和传参时加||[]一致,都可以避免空值报错。
内容的提问来源于stack exchange,提问作者GuyPeace
相关产品推荐
相关产品推荐

