将函数参数传递给另一个组件reactjs

pass function argument to another component reactjs

我正在使用 AutobahnJS 我不知道如何在另一个组件中使用相同的连接。

我决定像这样将 session 参数传递给另一个组件来手动创建它,但这不起作用我不知道为什么

主要成分:

class App extends Component {


   componentWillMount(){
     this.Call();
    }

  Call = () => {
    var connection = new autobahn.Connection({ url: 'ws://127.0.0.1:9000/', realm: 'realm1' });

    connection.onopen = function Pass (session) {
      console.log(session, 'This I want to use it in anothr component')
    };

    connection.open();
  }
  render() {
    return (
        <div>
        <Two Pass={this.Pass} />
        </div>
    )
  }
}

export default App;

子组件

class Two extends Component {

this.props.Pass(session); // if I console.log session will get error
//How to console log session here

  render() {
    return (
        <div>
       Child component
        </div>
    )
  }
}

export default Two;

在另一个组件中使用 Autobahn 的相同连接(会话)的最佳方法是什么?

更新

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageNumber: 1
    }
    this.sessionVar = this.sessionVar.bind(this)
  }

也许你可以尝试这样的事情:

let sessionVar = undefined
class App extends Component {


   componentWillMount(){
     this.Call();
    }
  Call = () => {
    var connection = new autobahn.Connection({ url: 'ws://127.0.0.1:9000/', realm: 'realm1' });

    connection.onopen = function Pass (session) {
      console.log(session, 'This I want to use it in anothr component')
      sessionVar = session
    };

    connection.open();
  }
  render() {
    return (
        <div>
        <Two Pass={this.Pass} session={sessionVar} />
        </div>
    )
  }
}

你也可以使用状态,看起来像这样可能会更容易:

  Call = () => {
    var connection = new autobahn.Connection({ url: 'ws://127.0.0.1:9000/', realm: 'realm1' });

    connection.onopen = function Pass (session) {
      console.log(session, 'This I want to use it in anothr component')
      this.setState({session})
    };

    connection.open();
  }
  render() {
    return (
        <div>
        <Two session={this.state.session} />
        </div>
    )
  }
}

然后你可以在你的子组件中这样做:

class Two extends Component {
componentDidMount(){
console.log(this.props.session)

}

  render() {
    return (
        <div>
       Child component
        </div>
    )
  }
}

export default Two;