我正在尝试使用ReactJS旋转图像的预览。所以我首先允许渲染预览的上传功能,然后在用户点击上传之前我希望他们可以根据自己的喜好旋转图像。这就是我用来预览图像的内容:
class ImageUpload extends React.Component {
constructor(props) {
super(props);
this.state = {file: '',imagePreviewUrl: ''};
}
_handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
render() {
let {imagePreviewUrl} = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} />);
} else {
$imagePreview = (<div className="previewText"></div>);
}
return (
<div className="previewComponent">
<form onSubmit={(e)=>this._handleSubmit(e)}>
<input className="fileInput"
type="file"
onChange={(e)=>this._handleImageChange(e)} />
<button className="submitButton"
type="submit"
onClick={(e)=>this._handleSubmit(e)}>Upload Image</button>
</form>
<input type="button" value="< rotate" onClick="" />
<input type="button" value="rotate >" onClick="" />
<div className="imgPreview">
{$imagePreview}
</div>
</div>
)
}}
ReactDOM.render(<ImageUpload/>, document.getElementById("mainApp"));
这就是我试图用来旋转图像的原因:
class RotateIMG extends React.Component{
constructor(props){
super(props);
this.state = {
rotation: 0
}
this.rotate = this.rotate.bind(this);
this.rotateleft = this.rotateleft.bind(this);
}
rotate(){
let newRotation = this.state.rotation + 90;
if(newRotation >= 360){
newRotation =- 360;
}
this.setState({
rotation: newRotation,
})
}
rotateleft(){
let newRotation = this.state.rotation - 90;
if(newRotation >= 360){
newRotation =- 360;
}
this.setState({
rotation: newRotation,
})
}
render(){
const { rotation } = this.state;
return <div><img style={{transform: `rotate(${rotation}deg)`}} src={"//blog-assets.risingstack.com/2016/Jan/react_best_practices-1453211146748.png"} width="600" />
<input onClick={this.rotateleft} type="button" value="left" />
<input onClick={this.rotate} type="button" value="right" />
</div>
}
}
const element = <RotateIMG />
ReactDOM.render(element, document.getElementById('root'));
据我所知,这些似乎都可以自行解决,但我不知道从哪个方面开始协同工作,或者如果可能的话。任何帮助将不胜感激!
答案 0 :(得分:1)
看起来你真的很亲密!您实际上在render
方法中为条件渲染设置了良好的结构,现在不是返回div,而是返回RotateIMG
组件:
import RotateIMG from './rotateIMG.js';
...
render() {
const { imagePreviewUrl } = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = <RotateIMG src={imagePreviewUrl} />;
} else {
$imagePreview = <div className="previewText"></div>;
}
...
}
然后,您需要调整RotateIMG
组件以确保它已导出并停止将其直接呈现给根。
export default class RotateIMG extends React.Component{
...
render(){
const { rotation } = this.state;
return <div><img style={{transform: `rotate(${rotation}deg)`}} src={this.props.src} width="600" />
<input onClick={this.rotateleft} type="button" value="left" />
<input onClick={this.rotate} type="button" value="right" />
</div>
}
}
从RotateIMG
组件
const element = <RotateIMG />
ReactDOM.render(element, document.getElementById('root'));