无法在onChange prop的输入字段上输入值

时间:2019-04-15 19:30:02

标签: reactjs

选择编辑时,我无法在输入字段上输入值,我认为这可能是onChange问​​题。

我看到的是类似here的东西,但是代码似乎已经过时了,我使用的是受控组件,而不是引用。

enter image description here

enter image description here

Editable.js ,当单击编辑时,此组件将呈现输入字段

import React from 'react';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';

const Editable = (props) => (
    <div>
        <TextField
            id="outlined-name"
            label="Title"
            style={{width: 560}}
            name="title"
            value={props.editField}
            onChange={props.onChange}
            margin="normal"
            variant="outlined"/>

    </div>
)

export default Editable; 

PostList.js 呈现帖子项列表

import React, { Component } from 'react';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import moment from 'moment';
import {connect} from 'react-redux';
import {DeletePost} from '../actions/';
import Editable from './Editable';
const Styles = {
    myPaper: {
        margin: '20px 0px',
        padding: '20px'
    }
}
class PostList extends Component{
    constructor(props){
        super(props);
        this.state ={
        }
    }
    // Return a new function. Otherwise the DeletePost action will be dispatch each
     // time the Component rerenders.
    removePost = (id) => () => {
        this.props.DeletePost(id);
    }
    onChange = (e) => {
        e.preventDefault();
        // maybe their is issue with it calling title from name in the editable 
        // component
        this.setState({
            [e.target.title]: e.target.value
        })
    }
    render(){
        const {posts, editForm, isEditing} = this.props;
        return (
            <div>
                {posts.map((post, i) => (
                    <Paper key={i} style={Styles.myPaper}>
                        <Typography variant="h6" component="h3">
                        {/* if else teneray operator */}
                        {isEditing ? (
                             <Editable editField={post.title} onChange={this.onChange}/>
                        ): (
                            <div>
                                {post.title}
                            </div>    
                        )}         
                        </Typography>
                        <Typography component="p">
                            {post.post_content}
                            <h5>
                                by: {post.username}</h5>
                            <Typography color="textSecondary">{moment(post.createdAt).calendar()}</Typography>
                        </Typography>
                        {!isEditing ? (
                            <Button variant="outlined" type="submit" onClick={editForm}>
                                Edit
                            </Button>
                        ):(
                            <Button variant="outlined" type="submit" onClick={editForm}>
                                Update
                            </Button>
                        )}
                        <Button
                            variant="outlined"
                            color="primary"
                            type="submit"
                            onClick={this.removePost(post.id)}>
                            Remove
                        </Button>
                    </Paper>
                ))}
            </div>
        )
    }
}
const mapDispatchToProps = (dispatch) => ({
    // Pass id to the DeletePost functions.
    DeletePost: (id) => dispatch(DeletePost(id))
});
export default connect(null, mapDispatchToProps)(PostList);

Posts.js

import React, { Component } from 'react';
import PostList from './PostList';
import {connect} from 'react-redux';
import { withRouter, Redirect} from 'react-router-dom';
import {GetPosts} from '../actions/';
const Styles = {
    myPaper:{
      margin: '20px 0px',
      padding:'20px'
    }
    , 
    wrapper:{
      padding:'0px 60px'
    }
}
class Posts extends Component {
  state = {
    posts: [],
    loading: true,
    isEditing: false, 
  }
  async componentWillMount(){
    await this.props.GetPosts();
    this.setState({ loading: false })
    const reduxPosts = this.props.myPosts;
    const ourPosts = reduxPosts  
    console.log(reduxPosts); // shows posts line 35
  }

  formEditing = () => {

    if(this.state.isEditing){
      this.setState({
        isEditing: false
      });
    }

    else{
      this.setState({
        isEditing:true
      })
    }
  }


  render() {
    const {loading} = this.state;
    const { myPosts} = this.props
    if (!this.props.isAuthenticated) {
      return (<Redirect to='/signIn' />);
    }
    if(loading){
      return "loading..."
    }
    return (
      <div className="App" style={Styles.wrapper}>
        <h1> Posts </h1>
        <PostList  isEditing={this.state.isEditing} editForm={this.formEditing} posts={myPosts}/>
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  isAuthenticated: state.user.isAuthenticated,
  myPosts: state.post.posts
})
const mapDispatchToProps = (dispatch, state) => ({
  GetPosts: () => dispatch( GetPosts())
});
export default withRouter(connect(mapStateToProps,mapDispatchToProps)(Posts));

2 个答案:

答案 0 :(得分:1)

您正在使用属性this.props.posts[index].title设置输入的值,但是您正在通过PostList的状态来处理更改。

您应该将onChange函数委派给将列表传递给PostList组件的组件,或者通过PostList的状态存储和更新列表。

答案 1 :(得分:1)

您需要传递更改功能中设置的值

onChange = (e) => {
    e.preventDefault();
    // maybe their is issue with it calling title from name in the editable 
    // component
    this.setState({
        [e.target.title]: e.target.value
    })
}

您正在设置编辑字段的状态。当您引用可编辑内容时,必须再次引用该值。

<Editable editField={this.state.[here should be whatever e.target.title was for editable change event] } onChange={this.onChange}/>

在可编辑组件中,将值设置为propeditField。

 <TextField
            id="outlined-name"
            label="Title"
            style={{width: 560}}
            name="title"
            **value={props.editField}**
            onChange={props.onChange}
            margin="normal"
            variant="outlined"/>

希望有帮助