如何在另一个JSX文件中访问并修改React自定义组件的state状态
问题原因
- React组件的内部state默认是私有的,父组件无法直接修改子组件的state值
- 你写在
<Whitebox>标签内部的内容会被当作children属性传递给Whitebox组件,不会触发state赋值逻辑,自然无法更新图片
最优修改方案(适配你的使用场景)
你的场景下不需要把wbimage存在Whitebox的内部state,直接通过父组件传props即可,修改后代码如下:
1. 修改whitebox.jsx
import "./whitebox.css" import { Component } from 'react'; // 补全原代码遗漏的Component引入 class Whitebox extends Component { render() { return ( <div> <div className="wbdemo" > <div className="wbimgframe"> <center> {/* 这里改成从props取值即可,无需用内部state存储 */} <img src={this.props.wbimage || ''} alt="Given image will be displayed here"/> </center> </div> <div className="wbdemobookname"> <label>Book Name</label> </div> <div className="wbdemobookauthor"> <i><label>By </label> <label>Book Author</label></i> </div> </div> </div> ); } } // 可设置默认值,父组件没传对应props时默认显示空 Whitebox.defaultProps = { wbimage: '' } export default Whitebox;
2. 修改javaa.jsx
import Whitebox from "./whitebox"; import "./javaa.css"; import { Component } from 'react'; // 补全原代码遗漏的Component引入 class Javaa extends Component { render() { return ( <div> <br/><br/><br/><br/><br/> <div className="javaamp"> {/* 直接通过组件属性传递图片地址即可 */} <Whitebox wbimage="https://cdn.codegym.cc/images/article/960defdc-e2f5-48ac-8810-d8b4436a88a7/512.jpeg" /> </div> </div> ); } } export default Javaa;
若后续需要Whitebox内部也能修改wbimage的值
可以用状态提升方案:把wbimage对应的state放到父组件Javaa中维护,再把修改state的方法通过props传给Whitebox,父子组件都可以修改这个值。
内容的提问来源于stack exchange,提问作者Dipika Adak
相关产品推荐
相关产品推荐

