以React形式编辑图像

时间:2019-01-31 17:33:55

标签: reactjs express upload

我在React应用程序中有一个表单,我想编辑值,一切正常,但是我不知道如何处理图像。 这是创建个人资料的表单

onSubmit = e => {
e.preventDefault();

const {
  handle,
  status,
  bio,
  facebook,
  twitter,
  youtube,
  instagram,
  profileImage
} = this.state;

let formData = new FormData();

formData.append("handle", handle);
formData.append("status", status);
formData.append("bio", bio);
formData.append("facebook", facebook);
formData.append("twitter", twitter);
formData.append("youtube", youtube);
formData.append("instagram", instagram);
formData.append("profileImage", profileImage);

this.props.createProfile(formData, this.props.history); };

 onChange = e => {
switch (e.target.name) {
  case "profileImage":
    this.setState({ profileImage: e.target.files[0] });
    break;
  default:
    this.setState({ [e.target.name]: e.target.value });
}

};

这是编辑表单

componentDidMount() {
this.props.getCurrentProfile();
}

componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
  this.setState({ errors: nextProps.errors });
}

if (nextProps.profile.profile) {
  const { profile } = nextProps.profile;
  // if empty make empty string
  profile.bio = isEmpty(profile.bio) ? "" : profile.bio;
  profile.social = isEmpty(profile.social) ? {} : profile.social;
  profile.facebook = isEmpty(profile.social.facebook)
    ? ""
    : profile.social.facebook;
  profile.twitter = isEmpty(profile.social.twitter)
    ? ""
    : profile.social.twitter;
  profile.instagram = isEmpty(profile.social.instagram)
    ? ""
    : profile.social.instagram;
  profile.youtube = isEmpty(profile.social.youtube)
    ? ""
    : profile.social.youtube;
  profile.profileImage = isEmpty(profile.profileImage)
    ? ""
    : profile.profileImage;
  // set to state
  this.setState({
    handle: profile.handle,
    status: profile.status,
    bio: profile.bio,
    facebook: profile.facebook,
    twitter: profile.twitter,
    instagram: profile.instagram,
    youtube: profile.youtube,
    profileImage: profile.profileImage
  });
  }
 }

 onSubmit = e => {
 e.preventDefault();

 const {
  handle,
  status,
  bio,
  facebook,
  twitter,
  youtube,
  instagram,
  profileImage
} = this.state;

let formData = new FormData();

formData.append("handle", handle);
formData.append("status", status);
formData.append("bio", bio);
formData.append("facebook", facebook);
formData.append("twitter", twitter);
formData.append("youtube", youtube);
formData.append("instagram", instagram);
formData.append("profileImage", profileImage);

this.props.createProfile(formData, this.props.history);
};

onChange = e => {
 switch (e.target.name) {
   case "profileImage":
     this.setState({ profileImage: e.target.files[0] });
     break;
   default:
      this.setState({ [e.target.name]: e.target.value });
  }
 };

因此,我能够从州获取表单字段并填写编辑表单,并且可以根据需要显示图像,但是如果用户不选择图像,则希望图像保持不变新代码,如果您不选择任何内容,则当前代码会将图片清空。我希望我很清楚。

0 个答案:

没有答案