首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >ReactJs中的父级下出现多个字段

ReactJs中的父级下出现多个字段
EN

Stack Overflow用户
提问于 2019-09-19 11:48:47
回答 1查看 59关注 0票数 1

代码语言:javascript
运行
AI代码解释
复制
class CriteriaSetValue extends Component {
  state = {
  
    count: 0,

    tableName: "",
    fieldName:"",

    tables: [],
    fields: [],
    addLine: [],
    addField: []
  };

  onSubmit = e => {
    e.preventDefault();
    const addField = this.state.addField;
    const size = addField.length + 1;
    addField.push(size);
    this.setState({
      addField
    });

addNewLine = event => {
    event.preventDefault();
    const addLine = this.state.addLine;
    const size = addLine.length + 1;
    const nextLine = this.state.count + 1;
    addLine.push(size);
    this.setState({
      count: nextLine,
      addLine
    });
  };

 render() {
    const {showForm, tableName, fieldName } = this.state;

    const { props, state } = this;

    return (
      <React.Fragment>
      

        <div className="form-wrapper">
          <div className="row">
            <div className="col-10 container">
              <form onSubmit={this.submit} className="card">
                <div className="card-header">
                  <h3 className="card-title">
                    Criteria Set
                    {/* <Locale value="std.formupload" /> */}
                  </h3>
                </div>
                <div className="card-body">
                  <div className="row">
                    <div className="col-md-7 col-lg-8">
                     
                      <div className="add-line">
                        <Button
                          icon
                          labelPosition="left"
                          onClick={this.addNewLine}
                        >
                          Add Line
                          <Icon name="plus" />
                        </Button>
                        {this.state.addLine.map(index => {
                          return (
                            <div
                              className="field-line"
                              style={{ marginTop: "30px" }}
                              key={index}
                              id={index}
                            >
                              <h4 className="field-button">Line {index}</h4>
                              <Button
                                className="field-button"
                                icon
                                onClick={this.toggleForm}
                              >
                                <Icon name="box" />
                              </Button>
                            </div>
                          );
                          
                        })
                        }

                        {
                          this.state.addField.map(index => {
                          return (
                            <React.Fragment>
                              <div
                                className="field-button"
                                style={{
                                  marginTop: "20px",
                                  paddingLeft: "20px"
                                }}
                                key={index}
                                id={index}
                              >
                        
                                <h4
                                  className="field-button"
                                  onclick={this.addCriteriaValue}
                                >
                                  <span>
                                    table.field
                                   
                                  </span>
                                </h4>

                                <Button
                                  className="field-button"
                                  icon
                                  onClick={this.toggleDelete}
                                >
                                  <Icon name="delete calendar" />
                                </Button>
                              </div>
                              <br></br>
                            </React.Fragment>
                          );
                        })
                        }
                      </div>

                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </React.Fragment>
    );
  }
};

这在某种程度上与我试图实现的目标有关:https://codesandbox.io/s/3vqyo8xlx5

但我希望孩子出现在“添加孩子”按钮被点击的偏好下,而不是最后一个按钮上。

我正在努力使多个字段出现在每一行下,当line1,line2等旁边的按钮被单击时,但目前,字段跳到最后一行时,按钮被单击,它不会出现在适当的行上。

当单击"Add Line“按钮时,我可以显示行;当单击"Line #1”旁边的按钮时,我也可以显示字段。

我希望当单击字段按钮时,"Line #1“的字段显示在line1下,当单击它旁边的字段按钮时,"Line #2”的字段显示在line2下,依此类推

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-19 14:33:01

您可以尝试如下所示:

代码语言:javascript
运行
AI代码解释
复制
const AddButton = ({ label, onClick }) => (
  <button onClick={onClick}>
    {label} [+]
  </button>
)

const FieldData = ({ label, criterias, onAdd, onDelete }) => (
  <React.Fragment>
    <div
      className='field-button'
      style={{
        marginTop: '20px',
        paddingLeft: '20px'
      }}
    >
      <h4 className='field-button'>
        <AddButton
          label='Add criteria'
          onClick={onAdd}
        />
        <span>
          {label}
        </span>
      </h4>
      {criterias.map((item, idx) => (
        <p key={idx}>{item.id}</p>
      ))}
      <button
        className='field-button'
        onClick={onDelete}
      >
        Del [-]
      </button>
    </div>
    <br />
  </React.Fragment>
)

class App extends React.PureComponent {
  state = {
    lines: []
  }

  handleSubmit = e => {
    e.preventDefault()
    console.log('DATA TO SAVE ' + JSON.stringify(this.state.lines))
  }
  
  handleAddLine = event => {
    event.preventDefault()
    this.setState(prevState => ({
      ...prevState,
      lines: [
        ...prevState.lines,
        {
         id: (prevState.lines.length + 1),
         fields: []
        }
      ]
    }))
  }
  
  handleAddField = lineId => e => {
    e.preventDefault()
    this.setState(prevState => {
      const newLines = [ ...prevState.lines ]
      const curLine = newLines[newLines.findIndex(({ id }) => id === lineId)]

      curLine.fields.push({
        id: curLine.fields.length + 1,
        criterias: []
      })
      
       return {
        ...prevState,
        lines: newLines
      }
    })
  }

  handleAddCriteria = (lineId, fieldId) => event => {
    event.preventDefault()
    
    this.setState(prevState => {
      const newLines = [ ...prevState.lines ]
      const curLine = newLines[newLines.findIndex(({ id }) => id === lineId)]
      const curField =  curLine.fields[curLine.fields.findIndex(({ id }) => id === fieldId)]

      curField.criterias.push({
        id: curField.criterias.length + 1
      })
      
      return {
        ...prevState,
        lines: newLines
      }
    })
  }
  
  handleDeleteField = (lineId, fieldId) => event => {
    event.preventDefault()
    this.setState(prevState => {
      const newLines = [ ...prevState.lines ]
      const curLine = newLines[newLines.findIndex(({ id }) => id === lineId)]
      curLine.fields =  curLine.fields.filter(item => item.id !== fieldId)
      
      return {
        ...prevState,
        lines: newLines
      }
    })
  }
  
  render() {
    const { lines } = this.state

    return (
      <React.Fragment>
        <div className='form-wrapper'>
          <div className='row'>
            <div className='col-10 container'>
              <form
                onSubmit={this.handleSubmit}
                className='card' 
              >
                <div className='card-header'>
                  <h3 className='card-title'>
                    Criteria Set
                  </h3>
                </div>
                <div className='card-body'>
                  <div className='row'>
                    <div className='col-md-7 col-lg-8'>
                      <div className='add-line'>
                        <AddButton
                          label='Add Line'
                          onClick={this.handleAddLine}
                        />
                        {lines.map((line, idx) => {
                          return (
                            <React.Fragment key={idx}>
                              <div
                                className='field-line'
                                style={{ marginTop: '30px' }}
                              >
                                <h4 className='field-button'>
                                  Line {idx+1}
                                </h4>
                                <AddButton
                                  label='Add field'
                                  onClick={this.handleAddField(line.id)}
                                />
                              </div>
                              {line.fields.map((lField, idx) => (
                                <FieldData
                                  label={idx+1}
                                  criterias={lField.criterias}
                                  onAdd={this.handleAddCriteria(line.id, lField.id)}
                                  onDelete={this.handleDeleteField(line.id, lField.id)}
                                />
                              ))}                    
                            </React.Fragment>
                          )
                        })}
                      </div>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </React.Fragment>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
)
代码语言:javascript
运行
AI代码解释
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

我为状态定义了一个新的数据结构,因此最好考虑嵌套数据,并且我对代码进行了一些重构。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58010340

复制
相关文章
Vue如何在父级下使用v-slot的值
https://cn.vuejs.org/v2/guide/components-slots.html#%E4%BD%9C%E7%94%A8%E5%9F%9F%E6%8F%92%E6%A7%BD
javascript.shop
2019/11/26
1.6K0
vue 中父级样式深度覆盖子组件
项目需要的原因,在sub组件的父级list组件中需要用到xhcj组件,同时sub组件中也用到了xhcj组件,两个地方代码逻辑是相同,仅仅是样式有些微的差别,所以决定共用组件,然后覆盖样式。
py3study
2021/04/02
2K0
group by 多个字段
众所周知,group by 一个字段是根据这个字段进行分组,那么group by 多个字段的结果是什么呢?由前面的结论类比可以得到,group by 后跟多个子段就是根据多个字段进行分组 注:下面的例子是在网上找到的,仅供参考:
lin_zone
2018/10/10
7.4K0
解决子级css float 浮动而父级高度没有自适应导致子级溢出父级的问题
出现问题的代码: .divcss5{ width:500px; border:1px solid #000; padding:10px } .divcss5-lf{ float:left; width:220px; height:100px; background:#000 } .divcss5-rt{ float:right; width:230px; height:100px; background:#
飞奔去旅行
2019/06/13
1.5K0
解决子级css float 浮动而父级高度没有自适应导致子级溢出父级的问题
jquery获取父级一级节点的序号
结构为:          <ul id="zdcd" style="display:none">             <li>                <a href="#">业务处理</a>                <ul>                  <li><a href ="mantask.aspx">业务申报审批</a></li>                         <li><a href ="maninfo.aspx">申报规则设定</a></li>    
用户1075292
2018/01/23
2K0
hive 中 统计某字段json数组中每个value出现的次数
需要将json数组里的qd_title都提取出来转换成hive中的array数组。下面介绍两种方法
Meet相识
2018/09/12
10.7K1
reactjs
最近在学习react js,ReactJS是Facebook开发的用于构建用户界面的JAVASCRIPT库,利用其可以实现组件式开发。
用户1394570
2018/08/08
1.3K0
JS获取节点的兄弟,父级,子级元素的方法
jQuery.parent(expr)  找父亲节点,可以传入expr进行过滤,比如$("span").parent()或者$("span").parent(".class")
OECOM
2020/07/01
9.3K0
SQL 获取一行中多个字段的最大值
在 chaos(id,v1,v2,v3) 表中获取每个 id 对应的 v1、v2、v3 字段的最大值,v1、v2、v3 同为数值类型。
白日梦想家
2020/12/14
11.6K0
layui.tree 父级与子级取消关联
官方版本 layui.tree 选择父级元素,子集元素会被默认选中。 在网上浏览了一番解决方案,修改了一下源码 共享给大家。 /** @Name:layui.tree 树 @Author:s
九霄道长
2021/03/02
2.3K0
子串在父串中出现的次数PosCount
function  PosCount( const  Substr, S:  string ): Integer; var   vLen: Integer; begin   vLen : =  Length(Substr); if  vLen  = 0 then     Result : = 0 else     Result : =  (Length(S)  –  Length(StringReplace(S, Substr,  ” , [rfReplaceAll])))  div  vLen; end ;
全栈程序员站长
2021/08/09
6080
Java创建父级文件夹
/** * 创建父级文件夹 * * @param file * 完整路径文件名(注:不是文件夹) */ public static void createParentPath(File file) { File parentFile = file.getParentFile(); if (null != parentFile && !parentFile.exists()) { parentFile.mkdirs(); // 创建文件夹
試毅-思伟
2018/09/06
2.1K0
Hello ReactJS
前言 React学习前先搭好环境,官网的例子看着比较分散。结合webpack就可以体验完整的es6开发流程了。 源码:https://github.com/Ryan-Miao/hello-react-js/releases/tag/0.1 1. 环境搭建 涉及以下几个技术。但从hello world的角度说,目前先不用知道是干嘛的,先用来学习react,后面再去研究各个组件的功能。 Webpack - A module bundler Babel - A Javascript compiler ES6 -
Ryan-Miao
2018/03/13
1.3K0
Hello ReactJS
reactjs 使用异步终级解决方案 async,await实践
先上代码: async componentDidMount() { let t = this; console.log(this.props.location); t.tree.getPandectView({}, t.state.page, this.state.pageSize); await t.getProjectId(); let searchParams = { order: 'asc', projectId: t.props.location.query.p
杭州前端工程师
2018/06/15
5180
mongoose模糊搜索匹配多个字段
需求很简单,就是想根据搜索的内容 同时去匹配数据的title和tag  并返回 主要使用的方法是 db.find().or([])  // 加上'i' 不区分大小写 let search = '111'   let reg = new RegExp(search, "i");   await wallPaper     .find( //不放在or里面的搜索 正常填写       { visible: true }, //返回指定数据       {         _id: 1,       }  
biaoblog.cn 个人博客
2022/08/28
1.9K0
引用父pom下的jar报红
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
chenchenchen
2019/09/02
9520
引用父pom下的jar报红
在ReactJS体验ES6中的class类
你也可以使用类表达式定义类。但是不同于类表达式,类声明不允许再次声明已经存在的类,否则将会抛出一个类型错误。
JavaEdge
2021/03/15
1.8K0
MySQL允许在唯一索引字段中添加多个NULL值
我们可以看出,此约束不适用于除BDB存储引擎之外的空值。对于其他引擎,唯一索引允许包含空值的列有多个空值。
Java那些事儿
2020/07/21
10.1K0
MySQL允许在唯一索引字段中添加多个NULL值
isomorphic reactjs
web应用从最早静态页面、到php后台框架输出、到mv*为主的SPA、到基于node中层的直出,目前有人提出web的下次改变可能将是基于isomorphic javascript的前后台同构应用。
IMWeb前端团队
2019/12/03
2.8K0
isomorphic reactjs
点击加载更多

相似问题

ReactJS:在孩子的条件下渲染父级

113

从子级控制父级中的Reactjs状态

10

从ReactJs中的父级复制道具?

129

在ReactJs中更改父级和子级的状态

12

ReactJS:访问父级中的子组件属性

14
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
社区富文本编辑器全新改版!诚邀体验~
全新交互,全新视觉,新增快捷键、悬浮工具栏、高亮块等功能并同时优化现有功能,全面提升创作效率和体验
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文