Javascript 显示react中每个动态div的组件

Javascript 显示react中每个动态div的组件,javascript,html,reactjs,render,Javascript,Html,Reactjs,Render,我正在尝试为动态生成的div呈现一个组件HomeScreen.js。我可以让它在某种程度上正常工作,但我无法将组件从动态生成的div中分离出来,而且我只尝试为单击的div呈现HomeScreen.js,但是我目前拥有的功能为所有div打开HomeScreen.js (这是一个联系人应用程序,动态生成的div是联系人。我只是尝试显示每个单击联系人的联系人信息) 我已经附上了当前功能的截图和我试图获得的功能的截图 我需要一些洞察力 import store from '../libs/store

我正在尝试为动态生成的div呈现一个组件HomeScreen.js。我可以让它在某种程度上正常工作,但我无法将组件从动态生成的div中分离出来,而且我只尝试为单击的div呈现HomeScreen.js,但是我目前拥有的功能为所有div打开HomeScreen.js

(这是一个联系人应用程序,动态生成的div是联系人。我只是尝试显示每个单击联系人的联系人信息)

我已经附上了当前功能的截图和我试图获得的功能的截图

我需要一些洞察力

import store from '../libs/store.js';
var jsforce = require('jsforce');

class menuScreen extends React.Component {

    constructor(props) {
        super(props)

        const data = store.getState();

        this.state = {

            username: '',
            messages: data.messages,
            records: [],
            showModal: false,
            showChat: false

        }
    }

    handleSearch(e) {
        this.setState({
            username: e.target.value
        })
    }

    handleChange(evt) {
        this.setState({
            username: evt.target.value.substr(0, 100)
        });

    }

    onClick(e) {
        e.preventDefault();
        this.setState({
            showChat: !this.state.showChat
        })
    }

    onLinkClicked() {


        var conn = new jsforce.Connection({
            serverUrl: 'https://cs63.salesforce.com',
            accessToken: sessionStorage.getItem('token')
        })

        var parent = this.state.username
        //console.log(this.state.username)
        conn.sobject("Contact").find({
                LastName: {
                    $like: parent
                }
            }, 'Id, Name, Phone, Account.Name'

        ).sort('-CreatedDate Name').
        limit(5).skip(10).execute(function(err, records) {
            if (err) {
                return console.error(err);
            }
            for (var i = 0; i < records.length; i++) {
                var record = (records[i]);
                console.log("Name: " + record.Name); 
                console.log("Phone: " + record.Phone);
                console.log("Account Name: " + record.Account.Name);

            }
            this.setState({
                records: records
            })

            this.setState({
                showChat: !this.state.showChat
            })

        }.bind(this))

    }

    render() {
        return (
            <div className='menubox' id='menubox'>

                <div className="boxbox">
                    <input className="search" type="text" placeholder="Contact Last Name" onChange={this.handleChange.bind(this)} value={this.state.username} />
                    <input className="submit" type="submit" onClick={this.onLinkClicked.bind(this)} value="GO" /></div>
                <div>
                    <div>
                        {this.state.records.map(record => (
                            <div className="info-block block-info clearfix">
                                <div className="square-box pull-left">
                                    <span className="glyphicon glyphicon-user glyphicon-lg"></span>
                                </div>
                                <h5>{record.Name}</h5>
                                <h4>{record.Phone}</h4>
                                <p>{record.Account.Name}</p>

                                    **//Trying to render home.js when Chat Bubble is clicked.**

                                    <a onClick={this.onClick.bind(this)}>
                                    <img src="./img/speechbubble.png" className="textIcon" />
                                     {this.state.showChat && < HomeScreen / >}
                                </a>
                            </div>
                        ))}
                    </div>

                </div>
            </div>

        )
    }

}

export default menuScreen;
从“../libs/store.js”导入存储;
var jsforce=require('jsforce');
类menuScreen扩展了React.Component{
建造师(道具){
超级(道具)
const data=store.getState();
此.state={
用户名:“”,
消息:data.messages,
记录:[],
showModal:错,
showChat:false
}
}
handleSearch(e){
这是我的国家({
用户名:e.target.value
})
}
手柄更换(evt){
这是我的国家({
用户名:evt.target.value.substr(01100)
});
}
onClick(e){
e、 预防默认值();
这是我的国家({
showChat:!this.state.showChat
})
}
onLinkClicked(){
var conn=新的jsforce.Connection({
服务器URL:'https://cs63.salesforce.com',
accessToken:sessionStorage.getItem('token')
})
var parent=this.state.username
//console.log(this.state.username)
conn.sobject(“联系人”)。查找({
姓氏:{
$like:家长
}
},'Id,Name,Phone,Account.Name'
).sort('-CreatedDate名称')。
限制(5).跳过(10).执行(函数)(错误,记录){
如果(错误){
返回控制台。错误(err);
}
对于(var i=0;i(
{record.Name}
{record.Phone}
{record.Account.Name}

**//尝试在单击聊天气泡时呈现home.js** {this.state.showChat&& ))} ) } } 导出默认菜单屏幕;
原因是,您使用单个
状态变量来控制所有
动态div
,您需要使用一个
数组,每个元素的每个值,因此在
状态变量中使用
showChat=[]
而不是
showChat=false
。要更改
onClick
函数中
array
的值,您需要传递
onClick
函数中元素的索引,并使用该索引更改特定值

对于其他更改,请检查代码和注释,它应该可以工作

使用以下命令:

import store from '../libs/store.js';
var jsforce = require('jsforce');

class menuScreen extends React.Component {

    constructor(props) {
        super(props)

        const data = store.getState();

        this.state = {
            username: '',
            messages: data.messages,
            records: [],
            showModal: false,
            showChat: []  //initially blank array
        }
    }

    handleSearch(e) {
        this.setState({
            username: e.target.value
        })
    }

    handleChange(evt) {
        this.setState({
            username: evt.target.value.substr(0, 100)
        });

    }

    onClick(i, e) { // pass the index on item clicked
        e.preventDefault();

        let showChat = this.state.showChat.slice();
        showChat[i] = !showChat[i];  //use that index to change the specific value
        this.setState({ showChat })
    }

    onLinkClicked() {

        var conn = new jsforce.Connection({
            serverUrl: 'https://cs63.salesforce.com',
            accessToken: sessionStorage.getItem('token')
        })

        var parent = this.state.username
        //console.log(this.state.username)
        conn.sobject("Contact").find({
                LastName: {
                    $like: parent
                }
            }, 'Id, Name, Phone, Account.Name'

        ).sort('-CreatedDate Name').
        limit(5).skip(10).execute((err, records) => { //use arrow function
            if (err) {
                return console.error(err);
            }
            // this loop is not required
            /*
            for (var i = 0; i < records.length; i++) {
                var record = (records[i]);
                console.log("Name: " + record.Name); 
                console.log("Phone: " + record.Phone);
                console.log("Account Name: " + record.Account.Name);

            }
            */
            console.log('recoreds values', records);
            this.setState({
                records: records,
            })
        })

    }

    render() {
        return (
            <div className='menubox' id='menubox'>

                <div className="boxbox">
                    <input className="search" type="text" placeholder="Contact Last Name" onChange={this.handleChange.bind(this)} value={this.state.username} />
                    <input className="submit" type="submit" onClick={this.onLinkClicked.bind(this)} value="GO" /></div>
                <div>
                    <div>
                        /*use the index also in map*/
                        {this.state.records.map((record, i) => (
                            <div className="info-block block-info clearfix">
                                <div className="square-box pull-left">
                                    <span className="glyphicon glyphicon-user glyphicon-lg"></span>
                                </div>
                                <h5>{record.Name}</h5>
                                <h4>{record.Phone}</h4>
                                <p>{record.Account.Name}</p>

                                   <a onClick={this.onClick.bind(this, i)}>
                                    <img src="./img/speechbubble.png" className="textIcon" />
                                     {this.state.showChat[i] && < HomeScreen / >}
                        {/*use this.state.showChat[i] specific value*/}
                                </a>
                            </div>
                        ))}
                    </div>

                </div>
            </div>

        )
    }

}

export default menuScreen;
直接使用:

onChange={this.handleChange}

我同意Mayank关于在showChat中使用数组的回答,但是基于这个想法,有什么原因不能让每个联系人都成为一个单独的组件?就我个人而言,我会渲染一系列子组件,比如Contact组件或其他东西,并从外部菜单屏幕组件中的状态向每个子组件传递道具

class Contact extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
  }

  render() {
    return (
      <div className="info-block block-info clearfix">
        <div className="square-box pull-left">
          <span className="glyphicon glyphicon-user glyphicon-lg"></span>
        </div>
        <h5>{record.Name}</h5>
        <h4>{record.Phone}</h4>
        <p>{record.Account.Name}</p>

        <a onClick={this.props.onClick}>
          <img src="./img/speechbubble.png" className="textIcon" />
          {this.props.showChat && < HomeScreen / >}
        </a>
      </div>
    )
  }
}
类联系人扩展了React.Component{
建造师(道具){
超级(道具)
this.state={}
}
render(){
返回(
{record.Name}
{record.Phone}
{record.Account.Name}

{this.props.showChat&& ) } }
然后您可以在menuScreen组件中使用它,如下所示:

import store from '../libs/store.js';
var jsforce = require('jsforce');


class menuScreen extends React.Component {

    constructor(props) {
        super(props)

        const data = store.getState();

        this.state = {
            username: '',
            messages: data.messages,
            records: [],
            showModal: false,
            showChat: []
        }
    }

    handleSearch(e) {
        this.setState({
            username: e.target.value
        })
    }

    handleChange(evt) {
        this.setState({
            username: evt.target.value.substr(0, 100)
        });

    }

    onClick(i, e) {
        e.preventDefault();

        let showChat = this.state.showChat.slice();
        showChat[i] = !showChat[i];
        this.setState({ showChat })
    }

    onLinkClicked() {

        var conn = new jsforce.Connection({
            serverUrl: 'https://cs63.salesforce.com',
            accessToken: sessionStorage.getItem('token')
        })

        var parent = this.state.username
        //console.log(this.state.username)
        conn.sobject("Contact").find({
                LastName: {
                    $like: parent
                }
            }, 'Id, Name, Phone, Account.Name'

        ).sort('-CreatedDate Name').
        limit(5).skip(10).execute((err, records) => {
            if (err) {
                return console.error(err);
            }
            // this loop is not required
            /*
            for (var i = 0; i < records.length; i++) {
                var record = (records[i]);
                console.log("Name: " + record.Name); 
                console.log("Phone: " + record.Phone);
                console.log("Account Name: " + record.Account.Name);

            }
            */
            console.log('recoreds values', records);
            this.setState({
                records: records,
            })
        })

    }

    render() {
        return (
            <div className='menubox' id='menubox'>

                <div className="boxbox">
                    <input className="search" type="text" placeholder="Contact Last Name" onChange={this.handleChange.bind(this)} value={this.state.username} />
                    <input className="submit" type="submit" onClick={this.onLinkClicked.bind(this)} value="GO" /></div>
                <div>
                    <div>
                        {this.state.records.map((record, i) => (
                          <Contact onClick={onClick.bind(this, i)} showChat={this.state.showChat[i]} />
                        ))}
                    </div>

                </div>
            </div>

        )
    }

}

export default menuScreen;
从“../libs/store.js”导入存储;
var jsforce=require('jsforce');
类menuScreen扩展了React.Component{
建造师(道具){
超级(道具)
const data=store.getState();
此.state={
用户名:“”,
消息:data.messages,
记录:[],
showModal:错,
showChat:[]
}
}
handleSearch(e){
这是我的国家({
用户名:e.target.value
})
}
手柄更换(evt){
这是我的国家({
用户名:evt.target.value.substr(01100)
});
}
onClick(即,e){
e、 预防默认值();
让showChat=this.state.showChat.slice();
showChat[i]=!showChat[i];
this.setState({showChat})
}
onLinkClicked(){
var conn=新的jsforce.Connection({
服务器URL:'https://cs63.salesforce.com',
accessToken:sessionStorage.getItem('token')
})
var parent=this.state.username
//console.log(this.state.username)
conn.sobject(“联系人”)。查找({
拉斯顿
import store from '../libs/store.js';
var jsforce = require('jsforce');


class menuScreen extends React.Component {

    constructor(props) {
        super(props)

        const data = store.getState();

        this.state = {
            username: '',
            messages: data.messages,
            records: [],
            showModal: false,
            showChat: []
        }
    }

    handleSearch(e) {
        this.setState({
            username: e.target.value
        })
    }

    handleChange(evt) {
        this.setState({
            username: evt.target.value.substr(0, 100)
        });

    }

    onClick(i, e) {
        e.preventDefault();

        let showChat = this.state.showChat.slice();
        showChat[i] = !showChat[i];
        this.setState({ showChat })
    }

    onLinkClicked() {

        var conn = new jsforce.Connection({
            serverUrl: 'https://cs63.salesforce.com',
            accessToken: sessionStorage.getItem('token')
        })

        var parent = this.state.username
        //console.log(this.state.username)
        conn.sobject("Contact").find({
                LastName: {
                    $like: parent
                }
            }, 'Id, Name, Phone, Account.Name'

        ).sort('-CreatedDate Name').
        limit(5).skip(10).execute((err, records) => {
            if (err) {
                return console.error(err);
            }
            // this loop is not required
            /*
            for (var i = 0; i < records.length; i++) {
                var record = (records[i]);
                console.log("Name: " + record.Name); 
                console.log("Phone: " + record.Phone);
                console.log("Account Name: " + record.Account.Name);

            }
            */
            console.log('recoreds values', records);
            this.setState({
                records: records,
            })
        })

    }

    render() {
        return (
            <div className='menubox' id='menubox'>

                <div className="boxbox">
                    <input className="search" type="text" placeholder="Contact Last Name" onChange={this.handleChange.bind(this)} value={this.state.username} />
                    <input className="submit" type="submit" onClick={this.onLinkClicked.bind(this)} value="GO" /></div>
                <div>
                    <div>
                        {this.state.records.map((record, i) => (
                          <Contact onClick={onClick.bind(this, i)} showChat={this.state.showChat[i]} />
                        ))}
                    </div>

                </div>
            </div>

        )
    }

}

export default menuScreen;