React人脸识别应用:无法传递box状态作为props导致样式不生效
React人脸识别应用:FaceRecognition组件样式不显示的问题解决
问题核心
问题根源是**setState调用语法错误**:你使用了this.setState=({box: box})的赋值写法,但setState是React组件的内置方法,必须通过函数调用触发。错误写法不会更新组件state,导致FaceRecognition组件接收不到包含位置属性的box props,自然渲染不出带样式的div。
错误写法与修正
错误代码
displayFaceBox = (box) => { console.log(box); // box参数正常 this.setState = ({box: box}); // 语法错误:直接赋值而非调用方法 }
正确写法
setState是方法,需通过括号调用并传入状态更新对象:
displayFaceBox = (box) => { console.log(box); this.setState({ box: box }); // 正确调用setState // 也可使用对象简写语法:this.setState({ box }) }
完整流程验证
- 位置计算确认:你已通过
console.log(box)确认参数正常,说明API请求和位置计算逻辑无问题。 - state更新验证:修正
setState调用后,组件state中的box会被正确更新,可通过console.log(this.state.box)在父组件渲染时验证。 - props传递与组件渲染:将更新后的state.box传递给FaceRecognition组件,组件即可用props生成样式:
// 父组件传递props <FaceRecognition box={this.state.box} imageUrl={this.state.imageUrl} /> // FaceRecognition组件内部渲染 const FaceRecognition = ({ imageUrl, box }) => { return ( <div className='center ma'> <div className='absolute mt2'> <img id='inputimage' alt='' src={imageUrl} width='500px' height='auto'/> <div className='bounding-box' style={{ top: box.top, right: box.right, bottom: box.bottom, left: box.left }} ></div> </div> </div> ); }
内容的提问来源于stack exchange,提问作者cem
相关产品推荐
相关产品推荐

