首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在React中禁用基于按钮的onChange值

在React中禁用基于按钮的onChange值
EN

Stack Overflow用户
提问于 2019-04-16 20:18:10
回答 1查看 66关注 0票数 0

我如何告诉onChange在update按钮上将禁用按钮设置为true,如果this.state.title小于3个字符,我做了一个尝试,但它不允许我输入一个值。它几乎破坏了代码。我希望更新被传递给redux。

这里是我的,免责声明一些代码已被删除,以更相关。

PostItem.js

代码语言:javascript
运行
复制
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 Editable from './Editable';
import {connect} from 'react-redux';
import {UpdatePost} from '../actions/';
const Styles = {
    myPaper: {
        margin: '20px 0px',
        padding: '20px'
    },
    button:{
        marginRight:'30px'
    }
}


class PostItem extends Component{

    constructor(props){
        super(props);

        this.state = {
            disabled: false,
        }
    }


    onUpdate = (id, title) => () => {
        // we need the id so expres knows what post to update, and the title being that only editing the title. 
        if(this.props.myTitle !== null){
            const creds = {
                id, title
            }
            this.props.UpdatePost(creds); 
        }

    }
    render(){
        const {title, id, removePost, createdAt, post_content, username, editForm, isEditing, editChange, myTitle, postUpdate} = this.props
        return(
            <div>
                   <Typography variant="h6" component="h3">
                   {/* if else teneray operator */}
                   {isEditing ? (
                    //  need a way to disable update button if the value is less than 3 characters 
                       <Editable editField={myTitle ? myTitle : title} editChange={editChange}/>
                   ): (
                       <div>
                           {title}
                       </div>    
                   )}         
                   </Typography>
                   <Typography component="p">
                       {post_content}
                       <h5>
                           by: {username}</h5>
                       <Typography color="textSecondary">{moment(createdAt).calendar()}</Typography>
                   </Typography>
                   {!isEditing ? (
                       <Button variant="outlined" type="submit" onClick={editForm(id)}>
                           Edit
                       </Button>
                   ):(

                       // pass id, and myTitle which as we remember myTitle is the new value when updating the title
                    //  how would i set disabled to false if the value from editField is less than 3 charaters.
                        <Button 
                            disabled={this.state.title.length > 3 }
                            variant="outlined" 
                            onClick={this.onUpdate(id, myTitle)}>
                            Update
                        </Button>
                   )}
                   <Button
                       style={{marginLeft: '0.7%'}}
                       variant="outlined"
                       color="primary"
                       type="submit"
                       onClick={removePost(id)}>
                       Remove
                   </Button>
           </div>
       )

    }

}

const mapStateToProps = (state) => ({
    disabled: state.post.disabled
})


const mapDispatchToProps = (dispatch) => ({
    // pass creds which can be called anything, but i just call it credentials but it should be called something more 
    // specific.
    UpdatePost: (creds) => dispatch(UpdatePost(creds)),
    // Pass id to the DeletePost functions.
});
export default connect(mapStateToProps, mapDispatchToProps)(PostItem);

正在从此editChange方法调用onChange。

PostList.js

代码语言:javascript
运行
复制
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, UpdatePost,EditChange, DisableButton} from '../actions/';
import PostItem from './PostItem';
const Styles = {
    myPaper: {
        margin: '20px 0px',
        padding: '20px'
    }
}
class PostList extends Component{
    constructor(props){
        super(props);
        this.state ={
            title: ''
        }
    }
    // 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();
        this.setState({
            title: e.target.value
        })


    }


    formEditing = (id) => ()=> {;

        this.props.EditChange(id);
    }

    render(){
        const {posts} = this.props;
        return (
            <div>
                {posts.map((post, i) => (
                    <Paper key={post.id} style={Styles.myPaper}>
                    {/* {...post} prevents us from writing all of the properties out */}
                        <PostItem
                             myTitle={this.state.title} 
                             editChange={this.onChange} 
                             editForm={this.formEditing} 
                             isEditing={this.props.isEditingId === post.id} 
                             removePost={this.removePost} 
                             {...post} 
                        />
                    </Paper>
                ))}
            </div>
        )
    }
}

const mapStateToProps = (state) => ({
    // disabled: state.post.disabled,
    isEditingId: state.post.isEditingId
})
const mapDispatchToProps = (dispatch) => ({
    // pass creds which can be called anything, but i just call it credentials but it should be called something more 
    // specific.
    EditChange: (id) => dispatch(EditChange(id)),
    UpdatePost: (creds) => dispatch(UpdatePost(creds)),
    // Pass id to the DeletePost functions.
    DeletePost: (id) => dispatch(DeletePost(id))
});
export default connect(mapStateToProps, mapDispatchToProps)(PostList);

this.props.DisableButton的动作

代码语言:javascript
运行
复制
export const DisableButton = () => {
    return(dispatch) => {
        dispatch({type:DISABLED});
    }
}

贴杆减速器,用于禁用按钮等

代码语言:javascript
运行
复制
import { DISABLED} from '../actions/';

const initialState = {,
    disabled: false,
    isEditingId:null
}

export default (state = initialState, action) => {
    switch (action.type) {

        case DISABLED:
            return({
                ...state,
                disabled:true
            })

        default:
            return state
    }
}

可编辑组件

代码语言:javascript
运行
复制
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.editChange}
            margin="normal"
            required
            variant="outlined"/>

    </div>
)

export default Editable; 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-16 21:14:28

您不需要调用DisableButton方法来禁用它的值。

修复您的onChange,可能大致如下:

代码语言:javascript
运行
复制
onChange = (e) => {
  this.setState({ title: e.target.value });
}

是的,这就足够了。

现在您可以使用一个逻辑来禁用Button组件,如下所示:

代码语言:javascript
运行
复制
<Button
  disabled={this.state.title.length <= 3}
  // rest of the attributes
/>

您不需要在redux上使用禁用的道具。这是不必要的,因为您可以直接在title组件上使用Button的本地状态来移动逻辑。

====编辑

您需要首先初始化this.state.title

代码语言:javascript
运行
复制
constructor(props) {
  super(props);

  this.state = {
    title: '',
  }

}

在提问者添加了一些细节之后,===第二次编辑

如果this.state.title位于PostList (父组件)组件上,并且您的Button通过myTitle支持来访问它,因为它位于PostItem组件上。你可以这样做:

代码语言:javascript
运行
复制
<Button
  disabled={this.props.myTitle.length <= 3}
  // rest of the attributes
/>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55716012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档