React - 需要下拉菜单来选择正确的选项(下拉菜单的选项值表示为字符串数字)

Posted

技术标签:

【中文标题】React - 需要下拉菜单来选择正确的选项(下拉菜单的选项值表示为字符串数字)【英文标题】:React - Need dropdown to select the correct option (option values for dropdown represented as string digits) 【发布时间】:2021-09-16 16:30:08 【问题描述】:

我正在尝试让我的下拉选项在更新我的friends 时预先选择正确的值。为了提供有关我的代码的上下文以及我的问题是在另一个名为 Friends 的组件上发生了什么,我渲染了朋友卡,每张卡都有一个更新按钮。如果单击该更新按钮,Route 路径将更改为 "/AddFriend/id",这会导致我的 AddFriend 组件呈现,然后我在我的 AddFriend 组件中使用我传递的 id 进行 ajax 调用 (getById)我的Friends 组件,以便获取有关该特定朋友的所有信息并使用该friend 的信息填充我的表单。我所有的表单输入字段都正确填充了正确的friend 信息,但我的问题是我作为下拉列表(不是输入字段)的 statusId。现在我可以更改选项标签上的value 属性以反映它在其中包含的值:

因此,如果我将选项标签从看起来像 <option value="NotSet">NotSet</option> 而不是 <option value="1">NotSet</option> 更改,这将导致我的下拉菜单选择正确的值,但我的导师说我需要这些值是数字(表示为字符串)。

例如,假设我单击的friend 的编辑按钮有一个statusId"Active",我希望我的应用程序知道这一点,因为我的statusId"Active" 然后我的下拉列表被选中值必须是<option value="2">Active</option>

    import React from "react";
    import Fade from '@material-ui/core/Fade';
    import * as FriendService from "../services/FriendService";
    
    class AddFriend extends React.Component 
    
        constructor(props) 
            super(props);
            this.state = 
                formData: 
                    title: "",
                    bio: "",
                    summary: "",
                    headline: "",
                    slug: "",
                    statusId: "",
                    skills: "",
                    primaryImage: ""
                
            ;
    
            this.onGetByIdSuccess = this.onGetByIdSuccess.bind(this);
            this.onGetByIdUpdateSuccess = this.onGetByIdSuccess.bind(this);
            this.onFormFieldChanged = this.onFormFieldChanged.bind(this);
        
    
        onFormFieldChanged = (e) => 
            let currentTarget = e.currentTarget;
            let newValue = currentTarget.value;
            let inputName = currentTarget.name;
    
            console.log(currentTarget, newValue);
            
            this.setState(() => 
                let formData = ...this.state.formData;
                formData[inputName] = newValue;
                return formData;
            );
        ;
    
        onSubmitClicked = () => 
            const data = ...this.state.formData;
            let friendId = this.props.match.params.friendId;
            console.log(data);
            if(!friendId) 
                FriendService.add(data)
                    .then(this.onAddFriendSuccess)
                    .catch(this.onAddFriendError);
            
            else 
                FriendService.update(friendId)
                    .then(this.onUpdateFriendSuccess)
                    .catch(this.onUpdateFriendError);
            
        ;
    
        onAddFriendSuccess(response) 
            console.log(response);
        
    
        onAddFriendError(err) 
            console.log(err);
        
    
        onUpdateFriendSuccess(response) 
            console.log(response);
        
    
        onUpdateFriendError(err) 
            console.warn(err);
        
    
        componentDidMount() 
    
            let friendId = this.props.match.params.friendId;
            console.log("ComponentDidMount", friendId);
    
            if(friendId)
    
                FriendService.getById(friendId)
                    .then(this.onGetByIdSuccess)
                    .catch(this.onGetByIdError);
            
        
    
        onGetByIdSuccess(response) 
            console.log(response);
            this.setState(
                formData: 
                    title: response.data.item.bio,
                    bio: response.data.item.bio,
                    summary: response.data.item.summary,
                    headline: response.data.item.headline,
                    slug: response.data.item.slug,
                    statusId: response.data.item.statusId,
                    skills: response.data.item.skills,
                    primaryImage: response.data.item.primaryImage.imageUrl,
                
            );
        
    
        onGetByIdError(err) 
            console.warn(err);
        
    
        componentDidUpdate(prevProps) 
    
            let currentPath = this.props.location.pathname;
            let previousPath = prevProps.location.pathname;
            console.log(currentPath, previousPath);
    
            let friendId = this.props.match.params.friendId;
            if(friendId && prevProps.match.params.friendId !== friendId)
                FriendService.getById(friendId)
                    .then(this.onGetByIdUpdateSuccess)
                    .catch(this.onGetByIdUpdateError);
            
    
          
    
          onGetByIdUpdateSuccess(response) 
            console.log(response);
            this.setState(
                formData: 
                    title: response.data.item.bio,
                    bio: response.data.item.bio,
                    summary: response.data.item.summary,
                    headline: response.data.item.headline,
                    slug: response.data.item.slug,
                    statusId: response.data.item.statusId,
                    skills: response.data.item.skills,
                    primaryImage: response.data.item.primaryImage.imageUrl,
                
            );
        
    
        onGetByIdUpdateError(err) 
            console.warn(err);
        
    
        render() 
            return(
                <Fade in=true style= transitionDelay:'250ms'>
                        <div className="p-2 mb-4 bg-light rounded-3">
                    <h4 style=
                        textAlign: 'center'
                    >Add a friend</h4>
                  <div className="container-fluid py-1">
                    <form>
                        <div className="form-group">
                            <label htmlFor="inputTitle">Title:</label>
                            <input type="text" className="form-control" id="inputTitle" name="inputTitle" defaultValue=this.state.formData.title></input>
                        </div>
                        <div className="form-group">
                            <label htmlFor="inputBio">Bio:</label>
                            <input type="text" className="form-control" id="inputBio" name="inputBio" defaultValue=this.state.formData.bio></input>
                        </div>
                        <div className="form-group">
                            <label htmlFor="inputSummary">Summary:</label>
                            <input type="text" className="form-control" id="inputSummary" name="inputSummary" defaultValue=this.state.formData.summary></input>
                        </div>
                        <div className="form-group">
                            <label htmlFor="inputHeadline">Headline:</label>
                            <input type="text" className="form-control" id="inputHeadline" name="inputHeadline" defaultValue=this.state.formData.headline></input>
                        </div>
                        <div className="form-group">
                            <label htmlFor="inputSlug">Slug:</label>
                            <input type="url" className="form-control" id="inputSlug" name="inputSlug" defaultValue=this.state.formData.slug></input>
                        </div>
                        <div className="form-group col-md-4">
                            <label htmlFor="statusId">Status Id</label>
                            <select name="statusId" id="statusId" className="form-control" onChange=this.onFormFieldChanged value=this.state.formData.statusId>
                            <option value="">Select Id Status</option>
                            <option value="1">NotSet</option>
                            <option value="2">Active</option>
                            <option value="3">Deleted</option>
                            <option value="4">Flagged</option>
                            </select>
                        </div>
                        <div className="form-group">
                            <label htmlFor="inputSkills">Skills</label>
                            <input type="text" className="form-control" id="inputSkills" name="inputSkills" defaultValue=this.state.formData.skills></input>
                        </div>
                        <div className="form-group">
                            <label htmlFor="inputPrimaryImg">Primary Image:</label>
                            <input type="url" className="form-control" id="inputPrimaryImg" name="inputPrimaryImg" defaultValue=this.state.formData.primaryImage></input>
                        </div>
                            <button id="register" type="button" className="btn btn-primary mr-3 m-3 mb-1" onClick=this.props.submit>Submit</button>
                            </form>
                        </div>
                    </div>
                </Fade>
                
            );
        
    
    
    export default AddFriend;

【问题讨论】:

【参考方案1】:

我让它工作了。这就是我所做的......

import React from "react";
import Fade from '@material-ui/core/Fade';
import * as FriendService from "../services/FriendService";

class AddFriend extends React.Component 

    constructor(props) 
        super(props);
        this.state = 
            formData: 
                title: "",
                bio: "",
                summary: "",
                headline: "",
                slug: "",
                statusId: "",
                skills: "",
                primaryImage: "",
            
        ;

        this.onGetByIdSuccess = this.onGetByIdSuccess.bind(this);
        this.onGetByIdUpdateSuccess = this.onGetByIdSuccess.bind(this);
        this.onFormFieldChanged = this.onFormFieldChanged.bind(this);
    

    onFormFieldChanged = (e) => 
        let currentTarget = e.currentTarget;
        let newValue = currentTarget.value;
        let inputName = currentTarget.name;

        console.log(currentTarget, newValue);
        
        this.setState(() => 
            let formData = ...this.state.formData;
            formData[inputName] = newValue;
            if(formData.statusId === "1")
                formData.statusId = "NotSet";
            
            if(formData.statusId === "2")
                formData.statusId = "Active";
            
            if(formData.statusId === "3")
                formData.statusId = "Deleted";
            
            if(formData.statusId === "4")
                formData.statusId = "Flagged";
            
            return formData;
        );
    ;

    onSubmitClicked = () => 
        const data = ...this.state.formData;
        let friendId = this.props.match.params.friendId;
        console.log(data);
        if(!friendId) 
            FriendService.add(data)
                .then(this.onAddFriendSuccess)
                .catch(this.onAddFriendError);
        
        else 
            FriendService.update(friendId)
                .then(this.onUpdateFriendSuccess)
                .catch(this.onUpdateFriendError);
        
    ;

    onAddFriendSuccess(response) 
        console.log(response);
    

    onAddFriendError(err) 
        console.log(err);
    

    onUpdateFriendSuccess(response) 
        console.log(response);
    

    onUpdateFriendError(err) 
        console.warn(err);
    

    componentDidMount() 

        let friendId = this.props.match.params.friendId;
        console.log("ComponentDidMount", friendId);

        if(friendId)

            FriendService.getById(friendId)
                .then(this.onGetByIdSuccess)
                .catch(this.onGetByIdError);
        
    

    onGetByIdSuccess(response) 
        console.log(response);
        this.setState(
            formData: 
                title: response.data.item.bio,
                bio: response.data.item.bio,
                summary: response.data.item.summary,
                headline: response.data.item.headline,
                slug: response.data.item.slug,
                statusId: response.data.item.statusId,
                skills: response.data.item.skills,
                primaryImage: response.data.item.primaryImage.imageUrl,
            
        );
    

    onGetByIdError(err) 
        console.warn(err);
    

    componentDidUpdate(prevProps) 

        let currentPath = this.props.location.pathname;
        let previousPath = prevProps.location.pathname;
        console.log(currentPath, previousPath);

        let friendId = this.props.match.params.friendId;
        if(friendId && prevProps.match.params.friendId !== friendId)
            FriendService.getById(friendId)
                .then(this.onGetByIdUpdateSuccess)
                .catch(this.onGetByIdUpdateError);
        

      

      onGetByIdUpdateSuccess(response) 
        console.log(response);
        this.setState(
            formData: 
                title: response.data.item.bio,
                bio: response.data.item.bio,
                summary: response.data.item.summary,
                headline: response.data.item.headline,
                slug: response.data.item.slug,
                statusId: response.data.item.statusId,
                skills: response.data.item.skills,
                primaryImage: response.data.item.primaryImage.imageUrl,
            
        );
    

    onGetByIdUpdateError(err) 
        console.warn(err);
    

    render() 
        return(
            <Fade in=true style= transitionDelay:'250ms'>
                    <div className="p-2 mb-4 bg-light rounded-3">
                <h4 style=
                    textAlign: 'center'
                >Add a friend</h4>
              <div className="container-fluid py-1">
                <form>
                    <div className="form-group">
                        <label htmlFor="inputTitle">Title:</label>
                        <input type="text" className="form-control" id="inputTitle" name="inputTitle" defaultValue=this.state.formData.title></input>
                    </div>
                    <div className="form-group">
                        <label htmlFor="inputBio">Bio:</label>
                        <input type="text" className="form-control" id="inputBio" name="inputBio" defaultValue=this.state.formData.bio></input>
                    </div>
                    <div className="form-group">
                        <label htmlFor="inputSummary">Summary:</label>
                        <input type="text" className="form-control" id="inputSummary" name="inputSummary" defaultValue=this.state.formData.summary></input>
                    </div>
                    <div className="form-group">
                        <label htmlFor="inputHeadline">Headline:</label>
                        <input type="text" className="form-control" id="inputHeadline" name="inputHeadline" defaultValue=this.state.formData.headline></input>
                    </div>
                    <div className="form-group">
                        <label htmlFor="inputSlug">Slug:</label>
                        <input type="url" className="form-control" id="inputSlug" name="inputSlug" defaultValue=this.state.formData.slug></input>
                    </div>
                    <div className="form-group col-md-4">
                        <label htmlFor="statusId">Status Id</label>
                        <select name="statusId" id="statusId" className="form-control" onChange=this.onFormFieldChanged value=this.state.formData.statusId>
                        <option value="">this.state.formData.statusId</option>
                        <option value="1">NotSet</option>
                        <option value="2">Active</option>
                        <option value="3">Deleted</option>
                        <option value="4">Flagged</option>
                        </select>
                    </div>
                    <div className="form-group">
                        <label htmlFor="inputSkills">Skills</label>
                        <input type="text" className="form-control" id="inputSkills" name="inputSkills" defaultValue=this.state.formData.skills></input>
                    </div>
                    <div className="form-group">
                        <label htmlFor="inputPrimaryImg">Primary Image:</label>
                        <input type="url" className="form-control" id="inputPrimaryImg" name="inputPrimaryImg" defaultValue=this.state.formData.primaryImage></input>
                    </div>
                        <button id="register" type="button" className="btn btn-primary mr-3 m-3 mb-1" onClick=this.props.submit>Submit</button>
                        </form>
                    </div>
                </div>
            </Fade>
            
        );
    


export default AddFriend;

【讨论】:

以上是关于React - 需要下拉菜单来选择正确的选项(下拉菜单的选项值表示为字符串数字)的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 React js 在下拉菜单中的选择选项上显示不同的组件

如何将选择标记选项值附加到Web服务角度4

选择下拉菜单后,动态输入字段无法正确显示

AngularJs 如何实现多级联动且最后一级下拉可以选择多个选项。请附上正确例子

Excel数据有效性设置的下拉菜单内容有多个,但选择时只能单选,如何设置下拉菜单,可以在选择时多选?

Django表示错误:选择一个有效的选择。这种选择不是可用的选择之一