onClick事件在reactjs中打开父元素之外的另一个组件?

时间:2017-04-19 14:05:48

标签: javascript reactjs dom jsx

到目前为止,我有一个单页反应应用程序有两个组件。 MenuScreenHomeScreen。当单击SpeechBubble图标时,MenuScreen中的当前onClick事件将HomeScreen显示为MenuScreen的子节点。如何触发onClick以在MenuScreen外部显示HomeScreen组件?此屏幕截图显示了我尝试做的事情。

enter image description here

MenuScreen.js

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) { 
        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.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 / >}
                                </a>
                            </div>
                        ))}
                    </div>

                </div>
            </div>

        )
    }

}

export default menuScreen;

mainApp.js

class MainApp extends React.Component{
    constructor(){
        super();

        const data = store.getState();

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

        };



    }


    render(){
    return (
      <div>
      <MenuScreen />
      </div> 

        );
    }
}


export default MainApp;

HomeScreen.js

class HomeScreen extends React.Component {
    constructor(){
        super();

        //Redux podaci za "hardcoding"
        const data = store.getState();

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

        };




}






    render(){
    return (
        <div>
          <h2>HELLO</h2>
          <p>Cras facilisis urna ornare ex volutpat, et
          convallis erat elementum. Ut aliquam, ipsum vitae
          gravida suscipit, metus dui bibendum est, eget rhoncus nibh
          metus nec massa. Maecenas hendrerit laoreet augue
          nec molestie. Cum sociis natoque penatibus et magnis
          dis parturient montes, nascetur ridiculus mus.</p>

          <p>Duis a turpis sed lacus dapibus elementum sed eu lectus.</p>
        </div>
      );
    }

}

export default HomeScreen;

1 个答案:

答案 0 :(得分:0)

一个选项是有一个更高级别的组件,如Page,它包含了菜单和内容部分。然后Page将确定显示哪些内容。

您还提到过您正在使用单页应用。这可能是使用React Router的好时机。使用React Router,单击Home Screen链接将更改url,这将使组件映射到Router中,如下所示:

class App extends Component {
  render() {
    return (
      <Router history={hashHistory}>
        <Route path='/home' component={HomeScreen} />
      </Router>
    )
  }
}

您可能想要使用带有侧栏的React路由器(例如this one)来查看示例。