反应组件中的访问功能

时间:2017-05-26 09:46:50

标签: javascript reactjs redux

我看起来像dump component

export default class DumpComponent extends Component {
    renderSomething(something) {
        console.log(something)
    }

    render() {     
        return (
            <div>
                { this.renderSomething(something) }
            </div> 
        );
    }
}

我包含在container

export default class Container extends Component {
    ...

render() {
    <DumpComponent 
     // call function renderSomething() with a variable I pass from here
    />
    }

我如何使用renderSomething()中声明的变量Container调用函数container

2 个答案:

答案 0 :(得分:0)

使用子componentDidMount从父级和调用函数中获取prop。

class Child extends React.Component {
  componentDidMount() {
    this.method(this.props.val);
  }
  method(val) {
    console.log(val)
  }
  render() {
    return <h1>Hello World!</h1>
  }
}

class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child val='hello' />
      </div>
    );
  }
}

演示:https://jsfiddle.net/v123582/25ebngdd/

此外,它可以在render()

上调用函数
class Child extends React.Component {
  method(val) {
    alert(val);
  }
  render() {
    return <div>{ this.method(this.props.val) }</div>
  }
}

class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child val='hello' />
      </div>
    );
  }
}

演示:https://jsfiddle.net/v123582/gevzf9kx/

答案 1 :(得分:0)

一路:

export default class DumpComponent extends Component {
    renderSomething(something) {
        console.log(something)
    }

    render() {     
        return (
            <div>
                { this.renderSomething(this.props.something) }
            </div> 
        );
    }
}

export default class Container extends Component {
    ...

render() {
    <DumpComponent 
      something="The thing"
    />
}

导出函数togather with component在您的情况下可能很有用:

# DumpComponent .js
export default class DumpComponent extends Component {
}
export const doSomething(something) {
    console.log(something)
}

# Container.js
import DumpComponent, {doSomething} from 'DumpComponent'

class Container extends Component {

render() {
    <DumpComponent 
      something={doSomething("The thing")}
    />
}