将滑动条上的onchange函数转换为html图像



我试图改变样式,每当ReactSlider改变。例如,我想在React中增加滑块时添加亮度。我做到了,但我似乎不能得到的样式被添加到图像,每当滑块通过onchange事件。下面是代码:

import React, { Component } from 'react';
import { BsFileEarmarkPlus } from 'react-icons/bs';
import ReactSlider from 'react-slider';
class Edit extends React.Component {
constructor(props) {
super(props);
this.state = {
file: null,
}
this.ImageUpload = this.ImageUpload.bind(this);
this.ChangeImage = this.ChangeImage.bind(this);
}
ImageUpload(event) {
console.log(event.target.files[0]);
this.setState({
file: URL.createObjectURL(event.target.files[0]),
});
}
ChangeImage(props) {
console.log(props);
var amount = this.props + '%';
var imgStyles = {
filter: 'brightness(' + amount + ')'
}
}
render() {
return (
<div className="editor">
<h1>Editor</h1>
<label htmlFor="fileChoose"><BsFileEarmarkPlus />Upload
<input type="file" id="fileChoose" onChange={this.ImageUpload} />
</label>
<hr />
<div className="img-surround">
<img 
src={this.state.file} 
id="img"
style={imgStyles} />
</div>
<div className="edit-nav">
<ReactSlider
className="horizontal-slider"
defaultValue={0}
max={100}
min={-100}
thumbClassName="example-thumb"
trackClassName="example-track"
renderThumb={(props, state) => <div {...props}>{state.valueNow}</div>}
onChange={this.ChangeImage}
/>
</div>
</div>
);
}
}
export default Edit;

唯一的问题是imgStyles从render()外部调用时是未定义的。

因为你在'ChangeImage'函数中定义了'imgStyles'变量。您应该在类外定义这个变量,或者将其定义为状态变量。

var imgStyles = {};
class Edit extends React.Component {
...
ChangeImage(props) {
console.log(props);
var amount = this.props + '%';
imgStyles = {
filter: 'brightness(' + amount + ')'
}
}
...

...
constructor(props) {
super(props);
this.state = {
file: null,
imgStyles: {}
}
}
...
ChangeImage(props) {
console.log(props);
var amount = this.props + '%';
this.setState({ imgStyles: { filter: 'brightness(' + amount + ')' } });
}
...
<img 
src={this.state.file} 
id="img"
style={this.state.imgStyles} />
...

最新更新