账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    React使用map渲染了一组Input,但是不知道怎么输入,求各位大哥看看
    30
    0
    首先是state包含nums、examplesnums用于索引,examples用于保存用户输入const [nums, setNums] = useState([1])const [examples, setExamples] = useState([{ input: "", output: "" }, { input: "", output: "" }, { input: "", output: "" }])然后是render,关键点在最后两个<Input/>本来想使用examples直接保存每一组输入,使用替换的方式更新数据(位置在<label>Input:</label>处)但是发现使用这种方式输入框无法进行输入无奈改用switch这种笨笨的方式(位置在<label>Output:</label>处)请问是否有更好的解决办法??{nums.map(index => { return ( <div key={"example-" + index}> <button onClick={() => { if (nums.length === 3) { alert("at most 3 examples") } else { setNums([...nums, nums[nums.length - 1] + 1]) } }}>add one </button> &nbsp; {index !== 1 && <button onClick={() => { let numbers = nums.slice(0, nums.length - 1); setNums(numbers) }}>remove one</button>} <div className="example-label-wrap"> <label htmlFor="" style={{display: "block"}}> Example {index} </label> </div> <div className="example-edit-wrap"> <div className="input-example-wrap"> <label>Input:</label> <Input type='text' value={examples[index-1].input} onChange={(e) => { e.preventDefault() setExamples((oldExamples) => { let newExamples = oldExamples //替换 newExamples.splice(index - 1, 1, { input: e.target.value, output: "" }) return newExamples }) }}/> </div> <div className="output-example-wrap"> <label>Output:</label> <Input type='text' value={output} onChange={(e) => { e.preventDefault() switch (index) { case 1: setExample1({...example1,output:e.target.value}) break case 2: setExample2({...example2,output:e.target.value}) break case 3: setExample3({...example3,output:e.target.value}) break default: } }}/> </div> </div> </div> )})}
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 可口的草莓 普通会员 1楼

      在React中,你可以使用map函数来渲染一个数组。但是,你需要确保你传递给map函数的参数是一个函数,该函数将接受一个输入值,并返回一个输出值。

      例如,如果你有一个包含用户输入的数组,你可以这样使用map

      ```jsx const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 } ];

      const names = users.map(user => user.name);

      console.log(names); // 输出:['Alice', 'Bob', 'Charlie'] ```

      在这个例子中,map函数接受一个函数user => user.name,这个函数接受一个用户对象,并返回它的name属性。所以,map函数将返回一个包含用户名字的数组。

      如果你的输入是一个数组,你可以使用map函数来遍历它,并根据你的逻辑来处理每个元素。例如,如果你想要将每个用户的名字转换为大写,你可以这样做:

      ```jsx const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 } ];

      const names = users.map(user => user.name.toUpperCase());

      console.log(names); // 输出:['Alice', 'BOB', 'CHARLIE'] ```

      在这个例子中,map函数接受一个函数user => user.name.toUpperCase,这个函数接受一个用户对象,并返回它的name属性的字符串表示。所以,map函数将返回一个包含用户名字的大写字符串数组。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部