Cra*_*oiD 6 javascript prop reactjs
我的问题是这个.我有两个组成部分.第一个组件是图像裁剪器.第二个组件是我应该显示裁剪图像的组件.
我面临的问题是我可以将裁剪后的图像传递给我的第二个组件,但我必须按下裁剪图像的按钮并传递给第二个组件,两次.在第二次单击时,只有我的图像传递给第二个组件.但我只能通过一次单击在第一个组件中显示裁剪的图像.我认为这种情况正在发生,因为在反应状态下,状态变化不会立即发生.那么我该如何解决这个问题呢.
我的方法是prop在第一个组件中创建一个函数,因为this.props.croppedImage(this.state.preview.img);这this.state.preview.img是裁剪后的图像.在第二个组件中,我通过调用prop函数获得裁剪后的图像.
我的代码
第一部分(裁剪)
class CropperTest extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "beautiful",
scale: 1,
preview: null,
}
this.handleSave = this.handleSave.bind(this);
}
handleSave = () => {
const img = this.editor.getImageScaledToCanvas().toDataURL();
this.setState({
preview: {
img,
scale: this.state.scale,
}
})
this.props.croppedImage(this.state.preview.img);
}
setEditorRef = (editor) => {
this.editor = editor
}
render() {
return (
<div>
<div className="overlay"></div>
<div className="crop_div">
<AvatarEditor
image={this.props.cropImage}
ref={this.setEditorRef}
width={450}
height={450}
border={50}
color={[255, 255, 255, 0.6]} // RGBA
scale={this.state.scale}
rotate={0}
/>
</div>
<div className="zoom_slider text_align_center">
<input className="crop_btn" type='button' onClick={this.handleSave} value='Save'/>
</div>
</div>
)
}
}
export default CropperTest;
Run Code Online (Sandbox Code Playgroud)
第二部分
在这里,我基本上做了以下几点.
<CropperTest croppedImage = {this.getCroppedImg}/>
getCroppedImg(img){
alert("Perfect Storm");
this.setState({
previewImg:img
})
}
Run Code Online (Sandbox Code Playgroud)
RIY*_*HAN 16
我认为这种情况正在发生,因为在反应状态下,状态变化不会立即发生.那么我该如何解决这个问题呢?
setState(updater,[callback])
setState()排队组件状态的更改.该setState不会立即更新状态.setState()并不总是立即更新组件.它可以批量推迟更新或推迟更新.这使得this.state在调用setState()潜在的陷阱后立即阅读.相反,使用componentDidUpdate或setState回调(setState(updater, callback))
调用this.props.croppedImage在setStatecallback.You将得到更新组件的状态值.在你的情况下它this.state.preview
this.setState({
preview: {
img,
scale: this.state.scale,
}
}, () => {
this.props.croppedImage(this.state.preview.img);
})
Run Code Online (Sandbox Code Playgroud)
Ais*_*ale 10
不再支持回调setState。解决此问题的最佳方法是使用 auseEffect并将依赖变量设置为状态变量。
useEffect(() => {
//do operation on state change
},[stateVariable])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12269 次 |
| 最近记录: |